前言:這標題說的有點大了,當一回標題黨,以前在學JSP的時候提到了JSTL和EL表達式,因爲一直鍾情於Servlet,遲遲沒有更新別的,這回算是跳出來了。這回放個大招,用Spring+SpringMVC+Spring Jdbc Template,實現一個增刪改查加分頁,但重點不在這,個人重心在於JSTL和EL表達式,標題雖然有點大,但話糙理不糙,我真的是要自定義框架,固然,這個框架可大可小,大的我不敢說,用JSTL自定義標籤封裝個分頁仍是能夠的,也算補上JSTL和EL表達式的學習吧。對於那些一直跟着我跟新博客腳步的朋友,我提醒大家不要着急,你要是好奇就能夠先試着跟着個人案例試試手,不要看到SSM框架就說還沒學,不會啥的,哈哈,開玩笑,都沒學怎麼可能會呢,我說了,這篇的重點在於JSTL和EL表達式,重要的話說了不下三遍了,至於附加的SSM,我會持續跟新,會手把手帶你理解的,別急,別急,就當先認識一下SSM吧。css
我用的開發工具是IDEA,若是有不會用IDEA的朋友能夠看以前寫過的博客《IDEA新手使用教程》,我建的這是一個Maven項目,若是有朋友不知道Maven,能夠先看一下我以前寫的介紹Maven的博客《Maven》,不知道如何配置Maven環境的能夠看《Maven的安裝與配置》https://www.cnblogs.com/zyx110/p/10801666.html不知道如何在IDEA中建Maven項目的朋友能夠看《IDEA爲新手專業打造》,此案例還會用到Tomcat,一樣,不會在IDEA中配置Tomcat的朋友能夠看《IDEA爲新手專業打造》,好,完成這些,就能夠開始敲代碼了。html
寫以前先簡單介紹一下JSTL和EL表達式:前端
JSTL是Java中的一個定製標記庫集java
實現了JSP頁面中的代碼複用,基於標籤庫原理,重複率較高的代碼塊支持複用,提升效率mysql
書寫JSP頁面時可讀性更強,長得很像XML,方便前端查看和參與開發web
不一樣角色用戶登陸時顯示不一樣提示信息spring
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
在JSP頁面中導入JSTL標籤庫sql
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
使用out標籤輸出數據庫
<c:out value="Hello JSTL"></c:out>
普通表達式的寫法: <%=session.getValue("name") %>express
EL表達式寫法: <c:out value="${sessionScope.name}" />
用美圓符號「$」定界,內容包括在花括號「{ }」中;
² 一般狀況是通用的${user.sex}或${user["sex"]}
² "[ ]"還能夠用來進行集合元素中的定位${booklist[0].price}
² 當包含特殊字符時,必須使用"[ ]",例如:${user["first-name"]}
² 經過變量動態取值:${user[param]},例如:param能夠是name/sex/others
在實際開發過程當中不能出現大量的html+java代碼相混合的jsp頁面,可是有時候jsp標籤和第三方標籤知足不了正常的開發工做,這就須要開發人員將業務邏輯封裝到符合jsp規範的類或接口中,來本身定義標籤從而知足不一樣的開發需求。這樣作的缺點是會加劇開發的工做量,但在開發過程當中簡化了先後端的溝通,便於後期的維護,這點工做量也是微不足道的。咱們能夠本身定義一套標籤機制,讓徹底不懂寫代碼的人開發一套網站出來。
案例場景:
在頁面中顯示當前時間,格式:「當前時間爲:2017年8月1日 10:30:50」
<% SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String date = sdf.format(new Date()); %> 當前時間爲:<%=date %>
顯示結果:
第一步:編寫自定義標籤的業務邏輯處理類
package utils; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTag extends TagSupport { private String format="yyyy-MM-dd HH:mm:ss"; private String color="blue"; private String fontSize="12px"; public void setFormat(String format) { this.format = format; } public void setColor(String color) { this.color = color; } public void setFontSize(String fontSize) { this.fontSize = fontSize; } public int doStartTag() throws JspException { //自定義業務 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); String date = simpleDateFormat.format(new Date()); String htmlshow = "<p class='' style='font-size:"+fontSize+";color:"+color+"'>"+date+"</p>"; try { pageContext.getOut().print(htmlshow); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } }
第二步:在WEB-INF目錄下編寫*.tld文件註冊標籤
格式模板
<?xml version="1.0" encoding="utf-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>myshortname</short-name> <uri>http://mycompany.com</uri> <tag> <name>date</name> <tag-class>utils.DateTag</tag-class> <body-content>empty</body-content> <attribute> <name>format</name> <required>false</required> </attribute> <attribute> <name>color</name> <required>false</required> </attribute> <attribute> <name>fontSize</name> <required>false</required> </attribute> </tag> </taglib>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="z" uri="http://mycompany.com" %> <%@ taglib prefix="c" uri="http://mycompany.com" %> <html> <head> <title>顯示時間</title> </head> <body> <h1>index.jsp</h1> <c:date/> </body> </html>
項目結構
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Spring核心基礎依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--日誌相關--> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> </dependencies>
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--處理中文亂碼--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--設置訪問靜態資源--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.mp3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.mp4</url-pattern> </servlet-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--配置註解要掃描的包--> <context:component-scan base-package="controller"></context:component-scan> <context:component-scan base-package="dao"></context:component-scan> <context:component-scan base-package="Service"></context:component-scan> <context:component-scan base-package="pojo"></context:component-scan> <context:component-scan base-package="utils"></context:component-scan> <context:component-scan base-package="test"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!--配置spring-jdbcTemplate--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/bbb?useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事務--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--註冊事務註解驅動--> <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven> <!--配置訪問靜態資源--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> <mvc:resources mapping="/img/**" location="/img/"></mvc:resources> <!--配置視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置前綴--> <property name="prefix" value="/"></property> <!--配置後綴--> <property name="suffix" value=".jsp"></property> </bean> <!--建立文件上傳組件對象--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> </beans>
package pojo; public class Book { @Override public String toString() { return "Book{" + "id=" + id + ", bookname='" + bookname + '\'' + ", price=" + price + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } private int id; private String bookname; private int price; }
package pojo; import java.util.List; public class PageBean<T> { private int pageCode;//當前頁碼 private int totalPage;//總頁數 private int count;//總記錄數 private int pageSize;//每頁記錄數 private List<T> pageList;//每頁的數據 public PageBean(int pageCode, int pageSize, int count, List<T> pageList) { this.pageCode = pageCode; this.count = count; this.pageSize = pageSize; this.pageList = pageList; } public PageBean() { } public int getPageCode() { return pageCode; } public void setPageCode(int pageCode) { this.pageCode = pageCode; } public int getTotalPage() { int tp = count/pageSize; return count%pageSize==0 ? tp : tp+1; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<T> getPageList() { return pageList; } public void setPageList(List<T> pageList) { this.pageList = pageList; } }
package dao; import pojo.Book; import java.util.List; public interface BookDao { public List<Book> findByPage(int pageCode,int pageSize); public int count(); }
package dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import pojo.Book; import java.util.List; @Repository public class BookDaoImpl implements BookDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Book> findByPage(int pageCode, int pageSize) { String sql = "select * from book limit ?,?"; Object[] param = {(pageCode-1)*pageSize,pageSize}; return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Book>(Book.class),param); } @Override public int count() { String sql = "select count(*) from book"; return jdbcTemplate.queryForObject(sql,Integer.class); } }
package Service; import pojo.Book; import pojo.PageBean; public interface BookService { public PageBean<Book> findByPage(int pageCode,int pageSize); }
package Service; import dao.BookDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pojo.Book; import pojo.PageBean; @Service public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; @Override public PageBean<Book> findByPage(int pageCode, int pageSize) { return new PageBean<Book>(pageCode,pageSize,bookDao.count(),bookDao.findByPage(pageCode,pageSize)); } }
package controller; import Service.BookService; import com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import pojo.Book; import pojo.PageBean; import utils.RequestPage; @Controller @RequestMapping("/book") public class BookController { @Autowired private BookService bookService; @RequestMapping("/query") public String findByPage(Integer page, Model model){ page = RequestPage.getPage(page);//判斷是否爲空 PageBean<Book> pageBean = bookService.findByPage(page,RequestPage.PAGE_SIZE); model.addAttribute("pageBean",pageBean); return "book"; } }
package utils; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTag extends TagSupport { private String format="yyyy-MM-dd HH:mm:ss"; private String color="blue"; private String fontSize="12px"; public void setFormat(String format) { this.format = format; } public void setColor(String color) { this.color = color; } public void setFontSize(String fontSize) { this.fontSize = fontSize; } public int doStartTag() throws JspException { //自定義業務 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); String date = simpleDateFormat.format(new Date()); String htmlshow = "<p class='' style='font-size:"+fontSize+";color:"+color+"'>"+date+"</p>"; try { pageContext.getOut().print(htmlshow); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } }
package utils; import pojo.PageBean; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; public class PageTag extends TagSupport { private PageBean pageBean; private String url; public void setUrl(String url) { this.url = url; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() throws JspException { try { StringBuffer sb = new StringBuffer(); //首頁 sb.append("<a href=\"" + url + "?page=1\">首頁</a> "); //上一頁 if (pageBean.getPageCode() <= 1) { sb.append("<span style=\"color: #555;\">上一頁</span> "); } else { sb.append("<a href=\"" + url + "?page=" + (pageBean.getPageCode() - 1) + "\">上一頁</a> "); } //顯示頁碼 int begin, end; if (pageBean.getTotalPage() <= 10) { begin = 1; end = pageBean.getTotalPage(); } else { begin = pageBean.getPageCode() - 5; end = pageBean.getPageCode() + 4; if (begin < 1) { begin = 1; end = 10; } else if (end > pageBean.getTotalPage()) { begin = pageBean.getTotalPage() - 9; end = pageBean.getTotalPage(); } } for (int i = begin; i <= end; i++) { if (i == pageBean.getPageCode()) { sb.append("<span style=\"color:red;\">" + i + "</span> "); } else { sb.append("<a href=\"" + url + "?page=" + i + "\">[" + i + "]</a> "); } } //下一頁 if (pageBean.getPageCode() >= pageBean.getTotalPage()) { sb.append("<span style=\"color: #555;\">下一頁</span>"); } else { sb.append("<a href=\"" + url + "?page=" + (pageBean.getPageCode() + 1) + "\">下一頁</a> "); } //尾頁 sb.append("<a href=\"" + url + "?page=" + pageBean.getTotalPage() + "\">尾頁</a> \n" + " 頁碼" + pageBean.getPageCode() + "/" + pageBean.getTotalPage()); pageContext.getOut().print(sb.toString()); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } } RequestPage package utils; public class RequestPage { public static final int PAGE_SIZE =5; public static Integer getPage(Integer page){ if (page==null||page<1){ page=1; } return page; } }
<?xml version="1.0" encoding="utf-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>myshortname</short-name> <uri>http://mycompany.com</uri> <tag> <name>date</name> <tag-class>utils.DateTag</tag-class> <body-content>empty</body-content> <attribute> <name>format</name> <required>false</required> </attribute> <attribute> <name>color</name> <required>false</required> </attribute> <attribute> <name>fontSize</name> <required>false</required> </attribute> </tag> <tag> <name>page</name> <tag-class>utils.PageTag</tag-class> <body-content>empty</body-content> <attribute> <name>pageBean</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>url</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="z" uri="http://mycompany.com" %> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/book.css"> <html> <head> <title>圖書</title> </head> <body> <h1 align="center">圖書列表</h1> <hr> <table> <tr> <th>ID</th> <th>書名</th> <th>價格</th> </tr> <c:forEach var="book" items="${pageBean.pageList}"> <tr> <td>${book.id}</td> <td>${book.bookname}</td> <td>${book.price}</td> </tr> </c:forEach> </table> <div id="page"> <z:page url="${pageContext.request.contextPath}/book/query" pageBean="${pageBean}"></z:page> </div> </body> </html>
後面我會持續分享SSM框架知識,欲知後文如何,請看下回分解
*****************************************************************************************************
個人博客園地址:https://www.cnblogs.com/zyx110/
原文出處:https://www.cnblogs.com/zyx110/p/11295044.html