mysql分页 jsp+servlet+javabean实现

MYSQL分页总结
在软件开发的很多时候很多场合我们都需要用到分页技术,现在的分页技术很多,可是我知道的不多,像displaytag这样的分页插件我感受了一下的确很不错而且可以导出pdf,word,excel等格式的文件,但是我不怎么会用,所以避而远之,还是总结一下自己对mysql分页的总结吧。
分页是一个项目中的常用功能,在我的项目中,我在公告显示,会议显示,文件显示,员工显示模块均用到了分页功能。为了能够让代码复用,并且容易维护,总之在很多好处的诱惑下,我首先编写一个接口类,代码如下:
SplitPage.java
package dao;

import java.util.List;

/**
* @author lixiangyu
*
*/
public interface SplitPage {

//获取总记录数
int getTotalCount();
//获取总页数
int getTotalPage();
//按页获取记录
List queryPerPage(int page);
//设置每页显示的记录数
void setCountPerPage(int countPerPage);
}
从上面的接口中我们可以看到分页的一个基本思路,我们需要从四个方面进行考虑,分别为获取数据表里面的总记录数,设置每页显示的记录数,按页获取记录,以及获取总页数。获取总记录数和按页获取记录需要用SQL语句实现,但如何获取总页数?很简单,通过计算得出。
定义完接口类需要实现接口,但是在实现接口之前需要做一件事情,那就是连接数据库,在我的项目中我用的是MYSQL数据库,连接数据库代码如下所示:
DBUtil.java
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
* @author lixiangyu
*
*/
public class DBUtil {
private static String DBDRIVER = "com.mysql.jdbc.Driver";
private static String DBURL = "jdbc:mysql://localhost:3306/oasys?user=root&password=123456&useUnicode=true&characterEncoding=utf8";
private static Connection conn = null;

public DBUtil(){}

public static Connection getConnection(){
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL);
// System.out.println("数据库连接");
}catch(SQLException e){
e.printStackTrace();
}catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
if(conn==null)
System.out.println("conn is not null");
return conn;
}

public static void closeConnection(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){
e.printStackTrace();
}
}

}
对于数据库连接的代码就不做过多说明,很多人也肯定是将连接数据库的代码单独的存放为一个文件。
现在需要实现接口类,接口类代码如下所示:
package dao;

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

import javabean.Userinfo;

public class SplitPageImp implements SplitPage {

private int countPerPage=10; //每页显示是个元素

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;
@Override
//获取总记录数
public int getTotalCount() {
int totalCount = 0; //设置总记录数默认值为0
try{
conn = DBUtil.getConnection();
ps = conn.prepareStatement("select count(*) from userinfo");
rs = ps.executeQuery();
if(rs.next()){
totalCount = rs.getInt(1);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtil.closeConnection(rs, ps, conn);
}
return totalCount;
}

@Override
//获取总页数
public int getTotalPage() {
int totalCount = this.getTotalCount();
int totalPage = 0;
if(totalCount%countPerPage==0)
totalPage = totalCount/countPerPage;
else
totalPage = totalCount/countPerPage+1;
return totalPage;
}

@Override
//按页查询
public List<Userinfo> queryPerPage(int page) {
List<Userinfo> list = new ArrayList<Userinfo>(); //我是针对用户进行分页,Userinfo是我的javabean文件,里面只包含了元素的定义和set、get方法
int startRow = (page-1) * countPerPage; //定义开始页起始元素
try{
conn = DBUtil.getConnection();
ps = conn.prepareStatement("select * from userinfo limit ?,?");  //注意只有在mysql中是limit 第一个?表示开始的元素,第二个?表示结束的元素,在mysql中第一个元素的下标为0
ps.setInt(1, startRow);
ps.setInt(2, countPerPage);
rs = ps.executeQuery();
while(rs.next()){
//除了括号里面的1,2,3……也可以将数字换成定义的元素
Userinfo user = new Userinfo();
user.setUid(rs.getString(1));
user.setUname(rs.getString(2));
user.setUpassword(rs.getString(3));
user.setUsex(rs.getString(4));
user.setUphone(rs.getString(5));
user.setUemail(rs.getString(6));
user.setUposition(rs.getString(7));
user.setUinDate(rs.getString(8));
user.setUintro(rs.getString(9));
user.setFk_rid(rs.getString(10));
user.setFk_did(rs.getString(11));
user.setUstatus(rs.getString(12));
user.setLogin(rs.getString(13));
list.add(user);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtil.closeConnection(rs, ps, conn);
}
return list;
}

@Override
//设置每页显示记录数
public void setCountPerPage(int countPerPage) {
this.countPerPage = countPerPage;

}
}

UserDao.java
Public class UserDao{
public static SplitPage getUserIMP(){
return new SplitPageImp();
}
}
Bean文件就这样,很简单的写完了,然后开始写servlet,servlet里面如果是自己定义一个class然后将class写成servlet的话需要在web.xml里面进行配置servlet要不然是不能运行的,不信的话你可以试试,我是试过的,一个action始终是转不过去。Servlet代码如下所示:
package servlet;

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

import javabean.Userinfo;

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

import dao.DepartmentDao;
import dao.RoleDao;
import dao.UserDao;

public class UserManager extends HttpServlet {
private static final long serialVersionUID = 1L;
      
    public UserManager() {
        super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response); //注意此处,如果没有这句则接收不到jsp传来的action
}
Protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");

Userinfo user = new Userinfo();
String action = request.getParameter("action");

if(action.equals("showAllUser")){
int page = 1;
request.getParameter("page");
String p =request.getParameter("page");
if(p!=null){
page = Integer.parseInt(p);
}
int totalCount = UserDao.getUserIMP().getTotalCount();
int totalPage = UserDao.getUserIMP().getTotalPage();
List list = UserDao.getUserIMP().queryPerPage(page);
request.setAttribute("totalCount",new Integer(totalCount));
request.setAttribute("totalPage", new Integer(totalPage));
request.setAttribute("page", new Integer(page));
request.setAttribute("list", list);

this.forward(request, response, "/userinfo/userManager.jsp");
} //这句话除了这样写还可以这样写:request.getRequestDispatcher("/userinfo/userManager.jsp").forward(request, response);不同之处是要定义一个forward方法。

private void forward(HttpServletRequest request,HttpServletResponse response,String url)throws ServletException,IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}

}
至此后台全部完成,我觉得后台代码还是很容易理解的。
前台jsp页面如下所示,注意参数的传递:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList,java.util.List,java.sql.*,javabean.Userinfo,dao.UserDao,javabean.Role,dao.RoleDao,dao.DepartmentDao,javabean.Department " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.Iterator"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
</head>
<body>
<%
int totalCount=(Integer)request.getAttribute("totalCount");
int totalPage=(Integer)request.getAttribute("totalPage");
int p=(Integer)request.getAttribute("page");
List list=(List)request.getAttribute("list");
Iterator it=list.iterator();
%>
<center>
员工总人数:<font color="red" ><%=totalCount %></font>
当前页:<font color="red" ><%=p %></font>/<font color="red" ><%=totalPage %></font>
<table border="1" width="100%" cellpadding="0" cellspacing="0" bordercolor="#6ba6e0" >
<tr>
<th background="image/tablebj.gif">姓名</th>
<th background="image/tablebj.gif">性别</th>
<th background="image/tablebj.gif">角色</th>
<th background="image/tablebj.gif">部门</th>
<th background="image/tablebj.gif">修改</th>
<th background="image/tablebj.gif">删除</th>
</tr>
<%
while(it.hasNext()){
Userinfo userinfo=(Userinfo)it.next();
Role role=RoleDao.getRoleByID(userinfo.getFk_rid());
Department depart=DepartmentDao.getDepartById(userinfo.getFk_did());
%>
<tr>
<td><a href="<%=request.getContextPath() %>/UserManager?action=showOneUser&userid=<%=userinfo.getUid() %>"><%=userinfo.getUname() %></a></td>
<td><%=userinfo.getUsex() %></td>
<td><%=role.getRname() %></td>
<td><%=depart.getDname() %></td>
<td><a href="<%=request.getContextPath() %>/UserManager?action=userUpdate&userid=<%=userinfo.getUid() %>">修改</a></td>
<td><a href="<%=request.getContextPath() %>/UserManager?action=userDel&userid=<%=userinfo.getUid() %>" onclick="return confirm('确定删除该员工 信息?')">删除</a></td>
</tr>
<%}%>
</table>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="130" align="right">
<form action="<%=request.getContextPath() %>/UserManager?action=showAllUser" method="post">
跳转到<input type="text" name="page" size="3">页
</form>
</td>
<td width="20"></td>
<td width="290" align="left">
<%if(p==1){ %>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=1"> 首页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=(p+1) %>"> 下一页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=totalPage %>">末页</a>
<%}if(p==totalPage){ %>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=(p-1) %>">上一页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=1"> 首页</a>
<%}if(p!=1&&p!=totalPage){ %>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=1"> 首页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=(p-1) %>">上一页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=(p+1) %>"> 下一页</a>
<a href="<%=request.getContextPath() %>/UserManager?action=showAllUser&page=<%=totalPage %>">末页</a>
<%}%>
</td>
</tr>
</table>
</center>
</body>
</html>

就这样很简单的就可以实现mysql的分页。

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