通用分页进阶之jsp之自定义标签

简介: 通用分页进阶之jsp之自定义标签

1. pageBean改造和实体类

1.实体类

package com.niyin.entity;
public class Book {
  private int bid;
  private String bname;
  private float price;
  @Override
  public String toString() {
    return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
  }
  public int getBid() {
    return bid;
  }
  public void setBid(int bid) {
    this.bid = bid;
  }
  public String getBname() {
    return bname;
  }
  public void setBname(String bname) {
    this.bname = bname;
  }
  public float getPrice() {
    return price;
  }
  public void setPrice(float price) {
    this.price = price;
  }
}

2.改造好的pageBean

这是进阶的,想了解前面的请看通用分页之详解】

package com.niyin.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
 * 分页工具类
 *
 */
public class PageBean {
  private int page = 1;// 页码
  private int rows = 10;// 页大小
  private int total = 0;// 总记录数
  private boolean pagination = true;// 是否分页
/**
 * 增加一个属性url,保留上一次发生的请求地址
 * 增加一个属性paramMap,保留上一次发送请求携带的参数
 * reg.getparameterMap
 * 增加一个最大页的方法
 * 增加一个下一页的方法
 * 增加一个上一页的方法
 * 初始化pagebean
 * 
 */
  public int maxPage() {
return this.total % this.rows==0 ? this.total/this.rows:this.total/this.rows+1;
  }
  public int nextPage() {
    return this.page<this.maxPage()?this.page+1:this.page;
  }
  public int prevPage() {
    return this.page>1?this.page-1:this.page;
  }
  public void setRequest(HttpServletRequest req) {
//  初始化默认查询第几页的数据
    this.setPage(req.getParameter("page"));
    this.setRows(req.getParameter("rows"));
  this.setPagination(req.getParameter("Pagination"));
  this.setUrl(req.getRequestURI().toString());
  this.setParamMap(req.getParameterMap());
  }
  public void setPagination(String Pagination) {
if (StringUtils.isNotBlank(Pagination)) {
  this.setPagination(!"false".equals(Pagination));
}
  }
  public void setRows(String rows) {
    if (StringUtils.isNotBlank(rows)) {
      this.setRows(Integer.valueOf(rows));
    }
  }
  public void setPage(String page) {
  if (StringUtils.isNotBlank(page)) {
    this.setPage(Integer.valueOf(page));
  }
  }
  private String url;
  private  Map<String, String[]> paramMap;
  public String getUrl() {
    return url;
  }
  public void setUrl(String url) {
    this.url = url;
  }
  public Map<String, String[]> getParamMap() {
    return paramMap;
  }
  public void setParamMap(Map<String, String[]> paramMap) {
    this.paramMap = paramMap;
  }
  public PageBean() {
    super();
  }
  public int getPage() {
    return page;
  }
  public void setPage(int page) {
    this.page = page;
  }
  public int getRows() {
    return rows;
  }
  public void setRows(int rows) {
    this.rows = rows;
  }
  public int getTotal() {
    return total;
  }
  public void setTotal(int total) {
    this.total = total;
  }
  public void setTotal(String total) {
    this.total = Integer.parseInt(total);
  }
  public boolean isPagination() {
    return pagination;
  }
  public void setPagination(boolean pagination) {
    this.pagination = pagination;
  }
  /**
   * 获得起始记录的下标
   * 
   * @return
   */
  public int getStartIndex() {
    return (this.page - 1) * this.rows;
  }
  @Override
  public String toString() {
    return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
  }
}

2. 助手类和tld约束

1.助手类

package com.niyin.Tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.JspTag;
import com.niyin.util.PageBean;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
/**
 * @author 小李飞刀
 * @site www.zking.com
 */
public class PageTag extends BodyTagSupport {
    private PageBean pageBean;
    public PageBean getPageBean() {
        return pageBean;
    }
    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }
    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            out.print(toHTML());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }
    private String toHTML() {
        StringBuilder sb = new StringBuilder();
//        这里拼接的是一个上一次发送的请求以及携带的参数,唯一改变的就是页码
        sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
        sb.append("<input type='hidden' name='methodName' value='list'>");
        sb.append("<input type='hidden' name='page'>");
//        重要设置拼接操作,将上一次请求参数携带到下一次
        Map<String, String[]> paMap = pageBean.getParamMap();
        if(paMap !=null && paMap.size()>0){
            Set<Map.Entry<String, String[]>> entrySet = paMap.entrySet();
            for (Map.Entry<String, String[]> entry : entrySet) {
                for (String val : entry.getValue()) {
                    if(!"page".equals(entry.getKey())){
                        sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
                    }
                }
            }
        }
        sb.append("</form>");
        int page = pageBean.getPage();
        int max = pageBean.maxPage();
        int before = page > 4 ? 4 : page-1;
        int after = 10 - 1 - before;
        after = page+after > max ? max-page : after;
//        disabled
        boolean startFlag = page == 1;
        boolean endFlag = max == page;
//        拼接分页条
        sb.append("<ul class='pagination'>");
        sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage(1)'>首页</a></li>");
        sb.append("<li class='page-item "+(startFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.prevPage()+")'>&lt;</a></li>");
//        代表了当前页的前4页
        for (int i = before; i > 0 ; i--) {
            sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page-i)+")'>"+(page-i)+"</a></li>");
        }
        sb.append("<li class='page-item active'><a class='page-link' href='javascript:gotoPage("+pageBean.getPage()+")'>"+pageBean.getPage()+"</a></li>");
//        代表了当前页的后5页
        for (int i = 1; i <= after; i++) {
            sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page+i)+")'>"+(page+i)+"</a></li>");
        }
        sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>&gt;</a></li>");
        sb.append("<li class='page-item "+(endFlag ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
        sb.append("<li class='page-item go-input'><b>到第</b><input class='page-link' type='text' id='skipPage' name='' /><b>页</b></li>");
        sb.append("<li class='page-item go'><a class='page-link' href='javascript:skipPage()'>确定</a></li>");
        sb.append("<li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
        sb.append("</ul>");
//        拼接分页的js代码
        sb.append("<script type='text/javascript'>");
        sb.append("function gotoPage(page) {");
        sb.append("document.getElementById('pageBeanForm').page.value = page;");
        sb.append("document.getElementById('pageBeanForm').submit();");
        sb.append("}");
        sb.append("function skipPage() {");
        sb.append("var page = document.getElementById('skipPage').value;");
        sb.append("if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+max+") {");
        sb.append("alert('请输入1~N的数字');");
        sb.append("return;");
        sb.append("}");
        sb.append("gotoPage(page);");
        sb.append("}");
        sb.append("</script>");
        return sb.toString();
    }
}

2.tld约束

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
  <description>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>http://java.niyin.com</uri>
  <validator>
    <description>
        Provides core validation features for JSTL tags.
    </description>
    <validator-class>
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    </validator-class>
  </validator>
  <tag>
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <name>page</name>
    <tag-class>com.niyin.Tag.PageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>pageBean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>

3.selevt的使用

package com.niyin.servlet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.niyin.entity.Book;
import com.niyin.util.PageBean;
import Dao.BookDao2;
@WebServlet("/book.action")
public class BookServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   this.doPost(request, response);
  }
  @SuppressWarnings("unused")
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//          String bname = request.getParameter("bname");
//          Map<String, String[]> map = request.getParameterMap();
//           String url = request.getRequestURI().toString(); 
//    request.getRequestDispatcher("bookList.jsp").forward(request, response);
    PageBean pageBean=new PageBean();
    pageBean.setRequest(request);
    BookDao2 book=new BookDao2();
    Book b=new Book();
    b.setBname(request.getParameter("bname"));
    try {
      List<Book> books = book.list(b, pageBean);
      request.setAttribute("books", books);
      System.out.println(books);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    request.setAttribute("pageBean", pageBean);
    request.getRequestDispatcher("bookList.jsp").forward(request, response);
  }
}

4.字符编码过滤器的使用

1.使用注解的方式配置使用过滤器

package com.niyin.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 中文乱码处理
 * 
 */
@WebFilter("*.action")
public class EncodingFiter implements Filter {
  private String encoding = "UTF-8";// 默认字符集
  public EncodingFiter() {
    super();
  }
  public void destroy() {
  }
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // 中文处理必须放到 chain.doFilter(request, response)方法前面
    res.setContentType("text/html;charset=" + this.encoding);
    if (req.getMethod().equalsIgnoreCase("post")) {
      req.setCharacterEncoding(this.encoding);
    } else {
      Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
      Set set = map.keySet();// 取出所有参数名
      Iterator it = set.iterator();
      while (it.hasNext()) {
        String name = (String) it.next();
        String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
        for (int i = 0; i < values.length; i++) {
          values[i] = new String(values[i].getBytes("ISO-8859-1"),
              this.encoding);
        }
      }
    }
    chain.doFilter(request, response);
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
    if (null != s && !s.trim().equals("")) {
      this.encoding = s.trim();
    }
  }
}

5.测试前端代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.niyin.com" prefix="z" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
  href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
  rel="stylesheet">
<script
  src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
  padding: 0;
  width: 40px;
  height: 100%;
  text-align: center;
  margin: 0 6px;
}
.page-item input, .page-item b {
  line-height: 38px;
  float: left;
  font-weight: 400;
}
.page-item.go-input {
  margin: 0 10px;
}
</style>
</head>
<body>
  <form class="form-inline"
    action="${pageContext.request.contextPath }/book.action" method="post">
    <div class="form-group mb-2">
      <input type="text" class="form-control-plaintext" name="bname"
        placeholder="请输入书籍名称">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查询</button>
  </form>
  <table class="table table-striped bg-success">
    <thead>
      <tr>
        <th scope="col">书籍ID</th>
        <th scope="col">书籍名</th>
        <th scope="col">价格</th>
      </tr>
    </thead>
    <tbody>
    <c:forEach items="${books}" var="b">
      <tr>
        <td>${b.bid }</td>
        <td>${b.bname}</td>
        <td>${b.price}</td>
      </tr>
</c:forEach>
    </tbody>
  </table>
  <z:page pageBean="${pageBean}"></z:page>
  <form action="" id="pageBeanForm" method="post">
    <input type="hidden" name="page">
  </form>
  <ul class="pagination justify-content-center">
    <li class="page-item"><a class="page-link"
      href='javascript:gotoPage(1)'>首页</a></li>
    <li class="page-item"><a class="page-link"
      href='javascript:gotoPage(1)'>&lt;</a></li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item active"><a class="page-link" href="#">3</a></li>
    <li class="page-item disabled"><a class="page-link" href="#">&gt;</a></li>
    <li class="page-item disabled"><a class="page-link" href="#">尾页</a></li>
    <li class="page-item go-input"><b>到第</b><input class="page-link"
      type="text" id="skipPage" name="" /><b>页</b></li>
    <li class="page-item go"><a class="page-link"
      href="javascript:skipPage()">确定</a></li>
    <li class="page-item"><b>共666条</b></li>
  </ul>
  <script type='text/javascript'>
    function gotoPage(page) {
      document.getElementById('pageBeanForm').page.value = page;
      document.getElementById('pageBeanForm').submit();
    }
    function skipPage() {
      var page = document.getElementById('skipPage').value;
      if (!page || isNaN(page) || parseInt(page) < 1
          || parseInt(page) > 1122) {
        alert('请输入1~N的数字');
        return;
      }
      gotoPage(page);
    }
  </script>
</body>
</html>

运行结果

5.重要提示

上面有一些方法是没有的,这些方法可以在我的另一篇文章通用分页之详解】还有一些资源和方法和资源我都打包好了请自行下载

打包好的文件

目录
相关文章
|
Java
JSP自定义标签【下】
JSP自定义标签【下】
66 0
|
Java
jsp自定义标签
jsp自定义标签
78 1
|
6月前
|
缓存 安全 小程序
从基础到进阶:掌握Java中的Servlet和JSP开发
【6月更文挑战第23天】Java Web开发中的Servlet和JSP是关键技术,用于构建动态网站。Servlet是服务器端小程序,处理HTTP请求,生命周期包括初始化、服务和销毁。基础Servlet示例展示了如何响应GET请求并返回HTML。随着复杂性增加,JSP以嵌入式Java代码简化页面创建,最佳实践提倡将业务逻辑(Servlet)与视图(JSP)分离,遵循MVC模式。安全性和性能优化,如输入验证、HTTPS、会话管理和缓存,是成功应用的关键。本文提供了一个全面的学习指南,适合各级开发者提升技能。
50 7
|
6月前
|
Java 容器
JSP 教程 之 JSP 自定义标签 3
JSP自定义标签允许开发人员创建可重用的组件,简化页面逻辑。在JSP 2.0及以上版本,可通过继承`SimpleTagSupport`并覆写`doTag()`方法来创建自定义标签,如`HelloTag`,它有一个`message`属性。属性值通过setter方法`setMessage()`设置。在TLD文件中定义该属性后,可在JSP页面使用`&lt;ex:Hello message=&quot;This is custom tag&quot;/&gt;`来调用,输出定制的文本。
29 0
|
6月前
|
SQL JSON Java
老程序员分享:Jsp分页实例
老程序员分享:Jsp分页实例
36 0
|
6月前
|
Java 容器
JSP 教程 之 JSP 自定义标签 4
**JSP自定义标签允许创建用户定义的语言元素。它们转换为Servlet中的tag handler,在执行时由Web容器调用。使用SimpleTagSupport继承并重写doTag()方法可创建简单标签。标签可设置属性,如message,通过setter方法访问。TLD文件定义属性元数据,JSP页面则通过prefix和uri引用。例如,&lt;ex:Hello message=&quot;...&quot;/&gt; 显示定制消息。属性可配置为必需、类型、描述及是否为JspFragment。**
30 0
|
6月前
|
搜索推荐 Java 容器
JSP 教程 之 JSP 自定义标签 2
**JSP自定义标签允许用户创建个性化标签,简化页面逻辑。在JSP 2.0中,通过继承`SimpleTagSupport`并重写`doTag()`可创建简单标签处理器。示例展示了一个名为`Hello`的自定义标签,它接收并显示标签体内容。TLD文件配置了标签元数据,JSP页面引用该标签并展示“这是消息主体”。**
26 0
|
6月前
|
Java 容器
JSP 教程 之 JSP 自定义标签 1
**JSP自定义标签简介**:扩展JSP功能,创建用户定义标签,通过Servlet容器调用Tag Handler。在JSP 2.0中,使用SimpleTagHandlers简化定制。以&quot;Hello&quot;标签为例,创建`HelloTag`类继承`SimpleTagSupport`,重写`doTag()`打印消息。编译后,在`custom.tld`定义标签库,JSP页面引用后即可使用。例如 `&lt;ex:Hello/&gt;` 显示 &quot;Hello Custom Tag!&quot;。
31 0
|
7月前
|
前端开发 Java 数据库
【Spring原理进阶】SpringMVC调用链+JSP模板应用讲解
【Spring原理进阶】SpringMVC调用链+JSP模板应用讲解
|
7月前
|
Java 数据安全/隐私保护
Jsp自定义标签(foreach,dept,select)
Jsp自定义标签(foreach,dept,select)
48 0