jsp自定义标签分页

自定义标签分页大大简化了jsp页面的代码量,减少了代码的冗余,提高了代码的重用性。

第一步:建立分页实体page类

 1 package com.soda.util;
 2 /**
 3  * @description 分页实体类
 4  * @author line
 5  * @time   2016年8月28日11:16:50
 6  */
 7 public class Page {
 8     private int pageSize;//每页记录per
 9     private int totalSize;//总记录total
10     private int currentPage;//当前页page
11     private int totalPage;//总页数lastpage
12     private String url;//要链接的sevlet
13     public Page() {
14         // TODO Auto-generated constructor stub
15     }
16     public Page(int pageSize, int totalSize, int currentPage, int totalPage,
17             String url) {
18         super();
19         this.pageSize = pageSize;
20         this.totalSize = totalSize;
21         this.currentPage = currentPage;
22         this.totalPage = totalPage;
23         this.url = url;
24     }
25     public int getPageSize() {
26         return pageSize;
27     }
28     public void setPageSize(int pageSize) {
29         this.pageSize = pageSize;
30     }
31     public int getTotalSize() {
32         return totalSize;
33     }
34     public void setTotalSize(int totalSize) {
35         this.totalSize = totalSize;
36     }
37     public int getCurrentPage() {
38         return currentPage;
39     }
40     public void setCurrentPage(int currentPage) {
41         if (currentPage<=0) {
42             this.currentPage=1;
43         }else if(totalPage<=0){
44             this.currentPage = currentPage;
45         }else if (currentPage>=totalPage) {
46             this.currentPage=totalPage;
47         }else {
48             this.currentPage = currentPage;
49         }
50     }
51     public int getTotalPage() {
52         return totalPage;
53     }
54     public void setTotalPage(int totalPage) {
55         this.totalPage = totalPage;
56     }
57     public String getUrl() {
58         return url;
59     }
60     public void setUrl(String url) {
61         this.url = url;
62     }
63
64 }

第二步:建立分页标签类PageTag(页码样式自己可以更改)

package com.soda.util;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class PageTag extends TagSupport {
    private Page pi;// 持有页码对象的引用

    public Page getPi() {
        return pi;
    }

    public void setPi(Page pi) {
        this.pi = pi;
    }

    @Override
    public int doStartTag() throws JspException {
        StringBuffer txt = new StringBuffer();
        if (pi.getTotalSize() < 1) {
            PageContext pc = this.pageContext;
            JspWriter out = pc.getOut();
            txt.append("<br/><div style=‘font-size:25px;text-align: center‘>暂无查询结果</div>");
            try {
                out.append(txt.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            txt.append("<form action=‘" + pi.getUrl() + "‘ method=‘post‘>");
            txt.append("<table width=‘100%‘ border=‘0‘ cellspacing=‘0‘ cellpadding=‘0‘>");
            txt.append("<tr>");
            txt.append("<td width=‘20%‘ height=‘25‘>");
            txt.append("<table border=‘0‘ cellspacing=‘0‘ cellpadding=‘3‘>");
            txt.append("<tr>");
            txt.append("<td style=‘width:60px‘></td>");

            if (pi.getCurrentPage() == 1) {
                txt.append("<td style=‘width:60px‘><span>首页</span></td> ");
                txt.append("<td style=‘width:60px‘><span>上一页</span></td> ");
            } else {
                txt.append("<td style=‘width:60px‘><a href=‘" + pi.getUrl()
                        + "&currentPage=1‘>首页</a></td> ");
                txt.append("<td style=‘width:60px‘><a href=‘" + pi.getUrl()
                        + "&currentPage=" + (pi.getCurrentPage() - 1)
                        + "‘>上一页</a></td> ");
            }
            for (int i = 1; i <= pi.getTotalPage(); i++) {
                if (pi.getCurrentPage() == i) {
                    txt.append("<td style=‘width:30px‘>" + i + "</td>");
                    continue;
                }
                if (Math.abs(pi.getCurrentPage() - i) <= 3) {
                    txt.append("<td style=‘width:30px‘><a href=‘" + pi.getUrl()
                            + "&currentPage=" + i + "‘>" + i + "</a></td> ");
                    continue;
                }
                if (Math.abs(pi.getCurrentPage() - i) < 7) {
                    txt.append("<td style=‘width:30px‘>.</td>");
                    continue;
                }
            }
            if (pi.getCurrentPage() >= pi.getTotalPage()) {
                txt.append("<td style=‘width:60px‘><span>下一页</span></td>");
                txt.append("<td style=‘width:60px‘><span>尾页</span></td>");
            } else {
                txt.append("<td style=‘width:60px‘><a href=‘" + pi.getUrl()
                        + "&currentPage=" + (pi.getCurrentPage() + 1)
                        + "‘>下一页</a></td>");
                txt.append("<td style=‘width:60px‘><a href=‘" + pi.getUrl()
                        + "&currentPage=" + pi.getTotalPage()
                        + "‘>尾页</a></td> ");
            }
            txt.append("</tr></table></td>");
            txt.append("<td width=‘20%‘ align=‘center‘><table border=‘0‘ cellspacing=‘0‘ cellpadding=‘3‘>");

            txt.append("<tr>");
            txt.append("<td>");
            txt.append("<input type=‘image‘ src=‘houtai/images/next.gif‘ width=‘16‘ height=‘16‘ border=‘0‘ onclick=‘return tiao()‘/>");
            txt.append("<td><input name=‘currentPage‘ size=‘3‘ id=‘cid‘ style=‘width:25;height:18‘/>/页</td> ");
            txt.append("</tr></table></td>");

            txt.append(" <td width=‘20%‘ align=‘right‘>共" + pi.getTotalSize()
                    + "条记录显示到" + pi.getCurrentPage() + "/" + pi.getTotalPage()
                    + "</td>");
            txt.append("</tr></table></form>");
            PageContext pc = this.pageContext;
            JspWriter out = pc.getOut();
            try {
                out.print("<script> function tiao(){"
                        + "var id=document.getElementById(‘cid‘).value; "
                        + "if(id==null||id.length==0){"
                        + "alert(‘请输入页码‘); return false;} " + "if(isNaN(id)){"
                        + "alert(‘请输入数字‘); return false;} "
                        + "if(id.indexOf(‘ ‘)>=0){"
                        + "alert(‘页码不能是空或含有有空格!‘); return false;}"
                        + "if(parseInt(id)<1||parseInt(id)>"
                        + pi.getTotalPage() + "){"
                        + "alert(‘您输入的页码不在页码范围之内!‘); return false;}}"
                        + "</script>");
                out.print("<style>a{text-decoration: none;} "
                        + "a:visited{color:#333333;}" + "</style>");
                out.append(txt.toString());

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return Tag.EVAL_PAGE;
    }
}

第三步:建立分页标签pageTag.tld文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee " version="2.1">
 4
 5     <description>pageTag</description>
 6     <display-name>pageTag</display-name>
 7     <tlib-version>1.1</tlib-version>
 8     <short-name>PersonTag</short-name>
 9     <uri>http://page/PersonTag</uri>
10
11     <tag>
12         <name>page</name>
13         <tag-class>com.soda.util.PageTag</tag-class>
14         <body-content>empty</body-content>
15         <attribute>
16             <name>pi</name>
17             <required>true</required>
18             <rtexprvalue>true</rtexprvalue>
19         </attribute>
20     </tag>
21 </taglib>

第四步:jsp页面运用(页面顶部引入标签,页面底部引用标签)注意:是红色字体所在行

<%@page import="com.soda.bean.User"%>
<%@page import="com.soda.bean.UserCondition"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://page/PersonTag" prefix="page" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title></title>
<link href="houtai/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="houtai/js/main.js"></script>
<script type="text/javascript">
var xmlhttp;
var useid;
function forbiduser(id){
    useid=id;
    var ss=document.getElementById("userStateId"+id).innerHTML;
    var s;
    var ustate;
    if(ss=="启用"){
         ustate=1;
        s="禁用";
    }else{
         ustate=0;
        s="启用";
    }
    if (confirm(‘是否‘+s+‘?‘)){
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange=res;
        xmlhttp.open("get", "<%=basePath%>UserServlet?method=forbiduser&useId="+id+"&useState="+ustate, true);
        xmlhttp.send(null);
    }

}
function res() {
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
        var txt = xmlhttp.responseText;
        if(txt=="禁用"){
            document.getElementById("btstate"+useid).innerHTML="启用";
        document.getElementById("userStateId"+useid).innerHTML="禁用";
        }
        if(txt=="启用"){
            document.getElementById("btstate"+useid).innerHTML="禁用";
            document.getElementById("userStateId"+useid).innerHTML="启用";
        }
    }
}
//全选与反选
window.onload = function(){
        document.getElementById("userids").onclick = function(){
            var flag = this.checked;
            var items = document.getElementsByName("items");
            for(var i = 0; i < items.length; i++){
                items[i].checked = flag;
            }
        }
        var items = document.getElementsByName("items");
        for(var i = 0; i < items.length; i++){
            items[i].onclick = function(){
                //记录有多少个 items 被选中了
                var number = 0;
                for(var j = 0; j < items.length; j++){
                    if(items[j].checked){
                        number++;
                    }
                }
                document.getElementById("userids").checked = (items.length == number);
            }
        }
    }
</script>
</head>
<body><%-- <c:set value="${sessionScope.uc }" var="uu"></c:set> --%>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="3">
  <tr>
    <td style="height:25px; background-color:#f3f3f3; font-weight:bold" valign="top">
    &nbsp;&nbsp;&nbsp;&nbsp;当前位置:
    <img src="houtai/images/arrow.gif" align="absmiddle">&nbsp;&nbsp;soda创业教育平台&nbsp;&nbsp;
    <img src="houtai/images/arrow.gif" align="absmiddle">&nbsp;&nbsp;后台管理&nbsp;&nbsp;
    <img src="houtai/images/arrow.gif" align="absmiddle">&nbsp;&nbsp;用户管理</td>
  </tr>
  <tr>
    <td style="height:34px; background-image:url(houtai/images/main_header.gif); border-bottom:1px solid #cfd8e0; padding:0px">
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td width="20" height="34"><img src="houtai/images/main_headerL.gif" width="20" height="34"></td>
          <td style="color:#90c8e8;"><img src="houtai/images/icon_card.gif" width="16" height="16" align="absmiddle">&nbsp;&nbsp;<strong>用户管理</strong></td>
          <td align="right" class="white" style="padding-right:20px"><a href="<%=basePath %>UserServlet?method=addlookrole" class="barBtn"><img src="houtai/images/5.png" align="absmiddle"> 新增</a>
          <a href="javascript:history.go(-1);" class="barBtn" onClick="javascript:history.go(-1);"><img src="houtai/images/btn_left.gif" align="absmiddle"> 后退</a>
          <a href="javascript:history.go(+1);" class="barBtn" onClick="javascript:history.go(+1);"><img src="houtai/images/btn_right.gif" align="absmiddle"> 前进</a>
          <a href="javascript:history.go(0);" class="barBtn" onClick="javascript:history.go(0);"><img src="houtai/images/btn_refresh.gif" align="absmiddle"> 刷新</a></td>
        </tr>
    </table></td>
  </tr>
  <%
  UserCondition uc=(UserCondition)session.getAttribute("uc");
      if(uc==null){
          uc = new UserCondition("","",-1,-1);
      }
  %>

  <tr>
    <td style="height:30px; background-color:#bddbff; border-bottom:1px solid #cfd8e0;"><table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
      <form action="<%=basePath %>UserServlet" method="post">
      <TR>
        <th width="10%" align="center">用户登录名</th>
        <td width="20%" class="BGCgray">
        <input type="text" name="conseluname" id="textfield" value="<%=uc.getUserLoginName()==null?"":uc.getUserLoginName()%>"></td>
        <th width="10%" align="center">真实姓名</th>
        <td width="20%" class="BGCgray">
        <input type="text" name="conselruname" id="textfield2" value="<%=uc.getUserRealName()==null?"":uc.getUserRealName()%>"></td>
        <th width="10%" align="center"><STRONG>状态</STRONG></th>
        <td width="20%" class="BGCgray">
        <select name="userState" id="select2">
          <option <%=uc.getUserState()==-1?"selected=‘selected‘":""%> value="-1">全部</option>
          <option <%=uc.getUserState()==1?"selected=‘selected‘":""%> value="1">启用</option>
          <option <%=uc.getUserState()==0?"selected=‘selected‘":""%> value="0">禁用</option>
        </select></td>
        <th width="10%" align="center">
        <BUTTON style="HEIGHT:25px" onClick="javascript:if (confirm(‘查询数据?‘)) return true;else return false;">
        <img src="houtai/images/btn_search.gif" width="16" height="16" align="absmiddle"> 查询
        <input type="hidden" name="method" value="showuser">
        <input type="hidden" name="currentPage" value="1">
        </BUTTON></th>
        </TR>
        </form>
    </table></td>
  </tr>
  <tr>
    <td height="100%" valign="top">
    <div style="overflow:auto;height:100%; width:100%">
      <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <TR>
          <th align="center"><input type="checkbox" name="checkbox" id="userids"></th>
          <th align="center">用户姓名</th>
          <th align="center">登录名</th>
          <th align="center">联系电话</th>
          <th align="center">地址</th>
          <th align="center">邮箱</th>
           <th align="center">状态</th>
          <th width="200" align="center">操作</th>
          </TR>
        <c:forEach items="${users }" var="user">
        <TR>
          <TD align="center"><input type="checkbox" name="items" id="checkbox2"></TD>
          <TD align="center">${user.useName }</TD>
          <TD align="center">${user.useLoginName }</TD>
          <TD align="center">${user.usePhone }</TD>
          <TD align="center">${user.useAddress }</TD>
          <TD align="center">${user.useEmail }</TD>
          <TD align="center" id="userStateId${user.useId }">${user.useState==1?"启用":"禁用" }</TD>
          <TD width="200" align="center">
          <BUTTON style="height:21px; font-size:12px" onClick="javascript:if (confirm(‘查看该信息?‘)){ location.href=‘<%=basePath %>UserServlet?method=lookinfo&useId=${user.useId }‘; return true;}else return false;">查看
          </BUTTON>
          <BUTTON style="height:21px; font-size:12px" onClick="javascript:if (confirm(‘编辑该信息?‘)){ location.href=‘<%=basePath %>UserServlet?method=editinfo&useId=${user.useId }‘; return true;}else return false;">编辑
          </BUTTON>
          <BUTTON style="height:21px; font-size:12px" id="fid" onclick="forbiduser(${user.useId})"><span id="btstate${user.useId }">${user.useState==1?"禁用":"启用" }</span>
          </BUTTON>
          <BUTTON style="height:21px; font-size:12px" onClick="javascript:if (confirm(‘删除该信息?‘)){ location.href=‘<%=basePath %>UserServlet?method=deleteinfo&useId=${user.useId }‘; return true;}else return false;">删除
          </BUTTON>
          </TD>
        </TR>
        </c:forEach>
      </table>
      <page:page pi="${page }"/>
</body>
</html>

第六步:这里省略sevlet代码,分页标签实体类中的URL在servlet中设置。

时间: 2024-11-05 12:23:03

jsp自定义标签分页的相关文章

JSP自定义标签渲染时报Illegal to flush错误

javax.servlet.ServletException:Illegal to flush within a custom tag 此错误是因为在JSP页面中的某一个自定义标签的doStartTag或doEndTag中用了out.flush,而其他的自定义标签没有导致.可以去掉out.flush. JSP自定义标签渲染时报Illegal to flush错误,布布扣,bubuko.com

JSP 自定义标签 生命周期

1. 2. JSP 自定义标签 生命周期,布布扣,bubuko.com

JSP自定义标签开发入门《转》

JSP自定义标签开发入门 一般情况下开发jsp自定义标签需要引用以下两个包 import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; 首先我们需要大致了解开发自定义标签所涉及到的接口与类的层次结构(其中SimpleTag接口与SimpleTagSupport类是JSP2.0中新引入的). 目标1:自定义一个用表格显示用户信息的简单标签 效果图: 在jsp页面使用此自定义标签: 假设我们有一个UserInfo的javabean,那

整理一份jsp自定义标签以及权限控制标签

jsp自定义标签使用场景因地制宜,可以实现自定义的标签输出功能也可以实现权限的管理 1:先定义标签类 1-1:页面输出标签 package com.suyin.web.jspsectag; import java.io.IOException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; public cla

一个简单的jsp自定义标签

学到了一个简单的jsp自定义标签,后面有更多的例子,会更新出来: 例子1: 步骤: 1.编写标签实现类: 继承javax.servlet.jsp.tagext.SimpleTagSupport; 重写doTag,实现在网页上输出: 2.在web-inf目录或其子目录下,建立helloword.tld文件,即自定义标签的说明文件 注意:标签处理类必须放在包中,不能是裸体类:不需要修改web.xml: //tld: tag lib description 标签库描述 java代码: package

JSP自定义标签配置

JSP自定义标签 <taglib> <taglib-uri>/WEB-INF/you.tld</taglib-uri> <taglib-location>/WEB-INF/you.tld</taglib-location> </taglib> 由这个配置可知,JSP自定义标签配置文件不是放在lib目录下,也不是放在classes文件夹中,更不是放在WebRoot目录下,而是放在WEB-INF目录下

JSP自定义标签开发入门

一般情况下开发jsp自定义标签需要引用以下两个包 import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; 首先我们需要大致了解开发自定义标签所涉及到的接口与类的层次结构(其中SimpleTag接口与SimpleTagSupport类是JSP2.0中新引入的). 目标1:自定义一个用表格显示用户信息的简单标签 效果图: 在jsp页面使用此自定义标签: 假设我们有一个UserInfo的javabean,那么在JSP页面使用此标签只

基于JSP 自定义标签使用实例介绍

添加JSP自定义标签: 先添加一个tld文件到WEB-INF文件夹中<?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://

jsp自定义标签tag EL函数

原文:jsp自定义标签tagEL函数 源代码下载地址:http://www.zuidaima.com/share/1550463459052544.htm 简单易懂的自定义EL函数 tag.java </pre><p> </p><pre name="code" class="java">package com.zuidaima.tag; import java.io.IOException; import javax.