java自定义分页标签

首先定义一个数据连接访问类
/**
*
*/
package com.aptech.jb.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author lyz
*
*/

public class DbCon {

/**
* 获取数据库连接
* @return 连接对象connection
*/
public static Connection getConn(){
Connection conn=null;
//驱动程序名
String driverName="com.mysql.jdbc.Driver";
//数据库名
String dbName="manager";
//数据库用户名
String userName="root";
//密码
String userPasswd="root";
//联结字符串
String url="jdbc:mysql://localhost:3306/"+dbName+"?useUnicode=true&characterEncoding=gb2312";
try{
Class.forName(driverName).newInstance();
conn=DriverManager.getConnection(url,userName,userPasswd);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return conn;
}

public static void main(String[] args) {
getConn();
}

    /**
     * 释放所有资源
     * @param rs
     * @param ps
     * @param conn
     */
public static void close(ResultSet rs,PreparedStatement ps,Connection conn){

try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
接下来,可以定义一个实体类的用户类
package com.aptech.jb.model;

public class User {
private int uid;
private String uname;
private String upass;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
}
接着,定义一个接口类UserDAO类,分别有分页的方法与统计总的记录数的方法
   package com.aptech.jb.dao;

import java.util.List;

import com.aptech.jb.model.User;

public interface UserDAO {
/**
* 以分页的方式来显示所有所有信息列表
* @param pageSize 每页显示的记录数
* @param pageNum 当前页码
* @return 当前页码的用户信息列表
*/
public List<User> findAllUserByPage(int pageSize, int pageNum);
   
/**
* 查找所有用户信息,用于分页时总页数的统计
* @return
*/
public int countUser();
}
然后,定义一个UserDAO的实现类UserDAOImpl类
   package com.aptech.jb.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.aptech.jb.dao.UserDAO;
import com.aptech.jb.db.DbCon;
import com.aptech.jb.model.User;

public class UserDAOImpl implements UserDAO{
private Connection conn=null;
private PreparedStatement ps=null;
private ResultSet rs=null;

public List<User> findAllUserByPage(int pageSize, int pageNum) {
String sql="select * from users where uid >=(select uid from users order By uid limit "+(pageNum-1)*pageSize+",1) limit "+pageSize;//分页查询语句
List<User> users=new ArrayList<User>();
try{
  conn=DbCon.getConn();//获取数据库连接
  ps=conn.prepareStatement(sql);//执行sql语句
  rs=ps.executeQuery();//执行查询操作
  while(rs.next()){
  User user=new User();
  user.setUid(rs.getInt("uid"));
  user.setUname(rs.getString("uname"));
  user.setUpass(rs.getString("upass"));
  users.add(user);//将分页后人员的所有信息都加入到集合对象中
  }
}catch(SQLException sqle){
sqle.printStackTrace();//异常处理
}finally{
DbCon.close(rs, ps, conn);//释放资源
}
return users;//返回结果集
}
public static void main(String[]args){
List<User> userList=new UserDAOImpl().findAllUserByPage(2, 2);
for(User user:userList){
System.out.println(user.getUname());
}
System.out.println(new UserDAOImpl().countUser());
}
public int countUser() {
String sql="select count(*) from users ";//sql语句
int result=0;
try {
ps=DbCon.getConn().prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
result=rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DbCon.close(null, ps, conn);//释放资源
}
return result;
}
}
再接下来,定义一个servlet类UserServlet,用于转发与重定向的作用
   package com.aptech.jb.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptech.jb.dao.UserDAO;
import com.aptech.jb.impl.UserDAOImpl;
import com.aptech.jb.model.User;


@SuppressWarnings("serial")
public class UserServlet extends HttpServlet {
private UserDAO userDao=new UserDAOImpl();
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

request.setCharacterEncoding("utf-8");
   response.setContentType("text/html;charset=utf-8");
   String pageSize=request.getParameter("pageSize");
   String pageNum=request.getParameter("pageNo");
   System.out.println(pageSize+"\t"+pageNum);
   if(pageSize==null || pageNum==null){
   pageSize="3";
   pageNum="1";
   }
 
   //System.out.println("当前页码为:"+pageNum+"\t每页显示的条数为:"+pageSize);
   int count=userDao.countUser();
   request.setAttribute("total", String.valueOf(count));
       List<User> userList=userDao.findAllUserByPage(Integer.parseInt(pageSize), Integer.parseInt(pageNum));
       if(userList!=null){
       request.setAttribute("userList", userList);
       request.getRequestDispatcher("/user_list.jsp").forward(request, response);
       }
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request,response);
}

}
关键的地方就是自定义标签的定义了,下面定义一个名为PageTag类的标签类
     package com.aptech.jb.pagerTag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

@SuppressWarnings("serial")
public class PageTag extends BodyTagSupport {
/**
* 每页显示的记录数
*/
    private int pageSize=5;
    /**
     * 提交的地址
     */
    private String action="";
    /**
     * 总的页数
     */
    private int totalRecords=1;
    /**
     * 当前的页码
     */
    public static final String PAGENO="pageNo";
    /**
     * 每页显示的记录数
     */
    public static final String PAGESIZE="pageSize";
    /**
     * 标签处理程序
     */
    public int doStartTag()throws JspException{
    int pageNo=1;
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
       
    String pageNum=request.getParameter("pageNo");
   
    if(pageNum!=null && !"".equals(pageNum)){
    pageNo=Integer.parseInt(pageNum);
    }
    //总页码
        int totalPage=1;
    //要输出到页面的HTML文本
    StringBuffer sb=new StringBuffer();
    sb.append("\r\n<form method='post'").append("name='pageForm'>\r\n");
    // 把当前页号设置成请求参数
        sb.append("<input type='hidden' name='").append(PAGENO).append("' value='").append(pageNo).append("'/>\r\n");
        sb.append("<input type='hidden' name='").append(PAGESIZE).append("' value='").append(pageSize).append("'/>\r\n");
        //计算总页数
        totalPage=getTotalPage();
        System.out.println("目前总页数为:"+totalPage);
        sb.append("<br/>\r\n");
        sb.append("&nbsp;\r\n");
        sb.append("共有").append(totalPage).append("页&nbsp;&nbsp;").append(totalRecords).append("条记录&nbsp;&nbsp;当前为第 ").append(pageNo).append(" 页\r\n");
        sb.append("&nbsp;\r\n");
       
        if(pageNo==1){
        sb.append("首页").append("&nbsp;").append("上一页").append("&nbsp;");
        }else{
        sb.append("<a href='javascript:turnOverPage(1)'>首页</a>\r\n").append("&nbsp;");
        sb.append("<a href='javascript:turnOverPage(").append(pageNo-1).append(")'>上一页</a>\r\n").append("&nbsp;");
        }
        if(pageNo==totalPage){
        sb.append("下一页").append("&nbsp;&nbsp;").append("尾页\r\n");
        }else{
        sb.append("<a href='javascript:turnOverPage(").append(pageNo+1).append(")'>下一页</a>\r\n").append("&nbsp;&nbsp;");
        sb.append("<a href='javascript:turnOverPage(").append(totalPage).append(")'>尾页</a>\r\n").append("&nbsp;");
        }
        sb.append("&nbsp;&nbsp;跳转到<select onchange='turnOverPage(this.value)'>\r\n");
        for(int i=1;i<=totalPage;i++){
        if (i ==pageNo) {
                 sb.append("  <option value='").append(i).append("' selected>第")
                 .append(i).append("页</option>\r\n");

            } else {
                 sb.append("  <option value='").append(i).append("'>第").append(i).append("页</option>\r\n");
           }
        }
        sb.append("</select>\r\n");
        sb.append("&nbsp;\r\n");
        sb.append("</form>\r\n");
       
        //生成提交表单的js脚本
        sb.append("<script type='text/javascript'>\r\n");
        sb.append(" function turnOverPage(num){\r\n");
        sb.append(" var form=document.pageForm;\r\n");
        sb.append("//页码越界的处理\r\n");
        sb.append(" if(num>").append(totalPage).append("){\r\n");
        sb.append(" no =").append(totalPage).append("\r\n");
        sb.append("}\r\n");
        sb.append(" if(num <= 0){\r\n");
        sb.append(" num=1;\r\n");
        sb.append("}\r\n");
        sb.append(" form.").append(PAGENO).append(".value=num;\r\n");
        sb.append(" form.action='").append(action).append("';\r\n");
        sb.append(" form.submit();\r\n");
        sb.append("}\r\n");
        sb.append("</script>\r\n");
       
        try{
        pageContext.getOut().println(sb.toString());
        }catch (IOException e){
        e.printStackTrace();
        }
        return super.doStartTag();
    }

public int getPageSize() {
return pageSize;
}

public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}

public String getAction() {
return action;
}

public void setAction(String action) {
this.action = action;
}

public int getTotalRecords() {
return totalRecords;
}

public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
/**
     * 根据总记录数得到总页数
     * @return int 总页数
     */
private int getTotalPage(){
int totalPage=(totalRecords%pageSize==0)?(totalRecords/pageSize):((totalRecords/pageSize+1));
return totalPage;
}
}
自定义标签完成后,还需要一个tld文件,不然页面上无法得知该自定义标签的uri及prefix
,于是,可以在/WEB-INF目录下创建一个pager.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">

  <tlib-version>0.9</tlib-version>

  <short-name>p</short-name>

  <uri>/WEB-INF/pager.tld</uri>

  <tag>

    <name>pager</name>

    <tag-class>com.aptech.jb.pagerTag.PageTag</tag-class>

    <body-content>scriptless</body-content>

    <attribute>

      <name>pageSize</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>
   
    <attribute>

      <name>totalRecords</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>
    <attribute>

      <name>action</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

  </tag>

</taglib>
完成后,仍需要在web.xml中配置pager.tld的uri及location,配置如下:
    <jsp-config>
       <taglib-uri>/myCustomPager.tld</taglib>
       <taglib-location>/WEB-INF/pager.tld</taglib-location>
    </jsp-config>
这样以后,就可以在页面上引用了,可以创建一个user_list.jsp的jsp文件:
    <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/WEB-INF/pager.tld" prefix="p"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
 
  <body>
   <table width="96%" border="0" align="center" cellpadding="4" cellspacing="1" class="yr_05">
    <tr bgcolor="#000000">
      <td height="23" colspan="5" class="yr_08" > 用户查询</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td width="9%" height="28" nowrap class="yr_07"> <div align="right">姓名:</div></td>
      <td width="22%" nowrap class="yr_07"> <input type="text" name="textfield" class="input">
      </td>
      <td width="69%" nowrap class="yr_07"> <input type="button" name="Submit" value="查询" class="button"></td>
    </tr>
  </table>
  <br>
  <table width="96%" border="0" align="center" cellpadding="0" cellspacing="1" class="yr_05">
    <tr>
      <td width="5%"  class="yr_06">&nbsp;</td>
      <td width="13%"  class="yr_06">ID</td>
      <td width="33%" nowrap  class="yr_06">名称</td>
      <td nowrap  class="yr_06">密码</td>
    </tr>
    <c:forEach items="${requestScope.userList}" var="user">
    <tr>
      <td height="20" align="center" nowrap class="yr_07"> <input type="checkbox" name="checkbox" value="checkbox"></td>
      <td nowrap class="yr_07"><a href="user_detail.htm">${user.uid}</a></td>
      <td nowrap class="yr_07">${user.uname}</td>
      <td nowrap class="yr_07">${user.upass}</td>
    </tr>
   </c:forEach>
     <p:pager pageSize="3" action="queryUser" totalRecords="${requestScope.total}"></p:pager>
  </table>
  </body>
</html>
当然,上面的例子完全是为了节省时间,而没有用SSH三大框架整合,不然数据访问层及低层的实现也不用个人编写,不足之处,还望赐教!!!

你可能感兴趣的:(java,sql,jsp,servlet,SQL Server)