1. 程式人生 > >SSM —— Jstl自制分頁標籤

SSM —— Jstl自制分頁標籤

首先需要兩個實體工具類

page省略get和set

public class Page<T> {   
	private int total;    // 總條數
	private int page;     // 當前頁
	private int size;     // 每頁數
	private List<T> rows; // 結果集
}

 NavigationTag

package com.etc.utils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
 * 顯示格式:首頁 上一頁 1 2 3 4 5下一頁 尾頁
 */
public class NavigationTag extends TagSupport {
	static final long serialVersionUID = 2372405317744358833L;
	/**
	 * request 中用於儲存Page<E> 物件的變數名,預設為“page”
	 */
	private String bean = "page";
	/**
	 * 分頁跳轉的url地址,此屬性必須
	 */
	private String url = null;
	/**
	 * 顯示頁碼數量
	 */
	private int number = 5;

	@Override
	public int doStartTag() throws JspException {
		JspWriter writer = pageContext.getOut();
		HttpServletRequest request = 
				(HttpServletRequest) pageContext.getRequest();
		Page page = (Page) request.getAttribute(bean);
		if (page == null)
			return SKIP_BODY;
		url = resolveUrl(url, pageContext);
		try {
			// 計算總頁數
			int pageCount = page.getTotal() / page.getSize();
			if (page.getTotal() % page.getSize() > 0) {
				pageCount++;
			}
			writer.print("<nav><ul class=\"pagination\">");
			//首頁連結路徑
			String homeUrl = append(url, "page", 1);
			//末頁連結路徑
			String backUrl = append(url, "page", pageCount);
			// 顯示“上一頁”按鈕
			if (page.getPage() > 1) {
				String preUrl = append(url, "page", page.getPage() - 1);
				preUrl = append(preUrl, "rows", page.getSize());
		writer.print("<li><a href=\"" + homeUrl + "\">" + "首頁</a></li>");
		writer.print("<li><a href=\"" + preUrl + "\">" + "上一頁</a></li>");
			} else {
writer.print("<li class=\"disabled\"><a href=\"#\">" + "首頁 </a></li>");
writer.print("<li class=\"disabled\"><a href=\"#\">" + "上一頁 </a></li>");
			}
			// 顯示當前頁碼的前2頁碼和後兩頁碼
			// 若1 則 1 2 3 4 5, 若2 則 1 2 3 4 5, 若3 則1 2 3 4 5,
			// 若4 則 2 3 4 5 6 ,若10 則 8 9 10 11 12
			int indexPage =1;
			if(page.getPage() - 2 <=0){
				indexPage=1;
			}else if(pageCount-page.getPage() <=2){
				indexPage=pageCount-4;
			}else{
				indexPage= page.getPage() - 2;
			}
    for (int i= 1;i <= number && indexPage <= pageCount;indexPage++,i++){
				if (indexPage == page.getPage()) {
			writer.print("<li class=\"active\"><a href=\"#\">" + indexPage
				+"<spanclass=\"sr-only\"></span></a></li>");
					continue;
				}
				String pageUrl = append(url, "page", indexPage);
				pageUrl = append(pageUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + pageUrl + "\">" + indexPage + "</a></li>");
			}
			// 顯示“下一頁”按鈕
			if (page.getPage() < pageCount) {
				String nextUrl = append(url, "page", page.getPage() + 1);
				nextUrl = append(nextUrl, "rows", page.getSize());
		writer.print("<li><a href=\"" + nextUrl + "\">" + "下一頁</a></li>");
		writer.print("<li><a href=\"" + backUrl + "\">" + "尾頁</a></li>");
			} else {
writer.print("<li class=\"disabled\"><a href=\"#\">" + "下一頁</a></li>");
writer.print("<li class=\"disabled\"><a href=\"#\">" + "尾頁</a></li>");
			}
			writer.print("</nav>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	private String append(String url, String key, int value) {
		return append(url, key, String.valueOf(value));
	}
	/**
	 * 為url 參加引數對兒
	 */
	private String append(String url, String key, String value) {
		if (url == null || url.trim().length() == 0) {
			return "";
		}
		if (url.indexOf("?") == -1) {
			url = url + "?" + key + "=" + value;
		} else {
			if (url.endsWith("?")) {
				url = url + key + "=" + value;
			} else {
				url = url + "&amp;" + key + "=" + value;
			}
		}
		return url;
	}
	/**
	 * 為url 新增翻頁請求引數
	 */
	private String resolveUrl(String url, 
        javax.servlet.jsp.PageContext pageContext) throws JspException {
		Map params = pageContext.getRequest().getParameterMap();
		for (Object key : params.keySet()) {
			if ("page".equals(key) || "rows".equals(key)){
				continue;
			}
			Object value = params.get(key);
			if (value == null){
				continue;
			}
			if (value.getClass().isArray()) {
				url = append(url, key.toString(), ((String[]) value)[0]);
			} else if (value instanceof String) {
				url = append(url, key.toString(), value.toString());
			}
		}
		return url;
	}
	public String getBean() {
		return bean;
	}
	public void setBean(String bean) {
		this.bean = bean;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public void setNumber(int number) {
		this.number = number;
	}
}    

commons.tld檔案

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
   PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
    <!-- 指定標籤庫的版本號 -->
    <tlib-version>2.0</tlib-version>
    <!-- 指定JSP的版本號 -->
    <jsp-version>1.2</jsp-version>
    <!-- 指定標籤庫的名稱 -->
    <short-name>common</short-name>
    <!-- 指定標籤庫的URI -->
    <uri>http://mypageutil.com/common/</uri>
    <!-- 指定標籤庫的顯示名稱 -->
    <display-name>Common Tag</display-name>
    <!-- 指定標籤庫的描述 -->
    <description>Common Tag library</description>
    <!-- 註冊一個自定義標籤 -->
    <tag>
        <!-- 指定註冊的自定義標籤名稱 -->
        <name>page</name>
        <!-- 指定自定義標籤的標籤處理器類 -->
        <tag-class>com.etc.utils.NavigationTag</tag-class>
        <!-- 指定標籤體型別 -->
        <body-content>JSP</body-content>
        <!-- 描述 -->
        <description>create navigation for paging</description>
        <!-- 指定標籤中的屬性 -->
        <attribute>
            <!-- 指定屬性名稱 -->
            <name>url</name>
            <!-- 該屬性為true時表示其指定是屬性為必須屬性 -->
            <required>true</required>
            <!-- 該屬性用於指定能不能使用表示式來動態指定資料,為true時表示可以 -->
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>bean</name> 
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>number</name> 
            <rtexprvalue>true</rtexprvalue>
        </attribute>
	</tag>
</taglib>

 mapper.xml

  <!--SQL片段  -->
  <sql id="selectStudentListWhere">
    <where>
      <if test="username != null" >
        username like "%"#{username}"%"
      </if>
      <if test="password != null" >
        OR password like "%"#{password}"%"
      </if>
      <if test="major != null" >
        OR major like "%"#{major}"%"
      </if>
    </where>
  </sql>
  <!-- 查詢客戶列表  -->
  <select id="selectStudentList" parameterType="com.etc.entity.Student"
          resultType="com.etc.entity.Student">
    select id, username, password,major from t_student
    <include refid="selectStudentListWhere"/>
    <!-- 執行分頁查詢 -->
    <if test="start !=null and rows != null">
      limit #{start},#{rows}
    </if>
  </select>
  <!-- 查詢客戶總數 -->
  <select id="selectStudentListCount" parameterType="com.etc.entity.Student"
          resultType="Integer">
    select count(*) from t_student
    <include refid="selectStudentListWhere"/>
  </select>

Dao

    // 客戶列表
    public List<Student> selectStudentList(Student student);
    // 客戶數
    public Integer selectStudentListCount(Student student);

service實現類

   public Page<Student> queryAllByJstl(Integer page, Integer rows, String username, String password) {
        // 建立客戶物件
        Student student = new Student();
        // 判斷客戶名稱
        if(StringUtils.isNotBlank(username)){
            student.setUsername(username);
        }
        // 判斷客戶資訊來源
        if(StringUtils.isNotBlank(password)){
            student.setPassword(password);
        }

        // 當前頁
        student.setStart((page-1) * rows) ;
        // 每頁數
        student.setRows(rows);
        // 查詢客戶列表
        List<Student> students =
                mapper.selectStudentList(student);
        // 查詢客戶列表總記錄數
        Integer count = mapper.selectStudentListCount(student);
        // 建立Page返回物件
        Page<Student> result = new Page<>();
        result.setPage(page);
        result.setRows(students);
        result.setSize(rows);
        result.setTotal(count);
        return result;
    }

controler

    @RequestMapping("/queryAllByJstl")
    public String list(@RequestParam(defaultValue="1")Integer page,
                       @RequestParam(defaultValue="5")Integer rows,
                       String username,String password, Model model) {
        // 條件查詢所有客戶
        Page<Student> studentPage = service.queryAllByJstl(page, rows, username,password);
        model.addAttribute("page", studentPage);
        return "queryAllByJstl";
    }

Student省略get和set

    private Integer id;
    private String username;
    private String password;
    private String major;
    private Integer start;            // 起始行
    private Integer rows;             // 所取行數

jsp頁面引用

<%@ taglib prefix="itheima" uri="http://mypageutil.com/common/" %>
<style>
    #mypage li{
        float: left;
        margin-left:6px;
        list-style: none;
    }
</style>
<form method="post">
    <table>
        <tr>
            <th>姓名</th>
            <th>密碼</th>
            <th>專業</th>
        </tr>
        <c:forEach var="c" items="${page.rows}">
            <tr>
                <td>${c.username}</td>
                <td>${c.password}</td>
                <td>${c.major}</td>
            </tr>
        </c:forEach>
    </table>

</form>
<div id="mypage">
    <itheima:page url="${pageContext.request.contextPath}/queryAllByJstl" />
</div>

實現效果