源码 点击打开链接
其他web项目传送门 http://blog.csdn.net/u011299745/article/details/53547279
有一个学生表,可以通过姓名进行模糊查找,或者性别查找。
使用subList()实现,步骤(MVC):
- (M)根据查询条件生成有一定信息的Student对象,查询出所有符合条件的学生,所有信息存储在List<Map<k,v>>中。
- 遍历结果,用Map<k,v>来实例化Student,所有符合条件的学生,存入List<Student>。(这个List就是通过输入条件查找到的所有结果,结果可能太多所以需要分页显示)
- 用上一步的List,和每页大小(pageSize)、当前页(pageNum)实例化一个Pager对象。Pager对象包含总页数,总条数,当前页,每页大小,当前页显示的对象(使用List.subList()来截取)。用传入的参数可以计算出来。
- (C)在servlet中初始化参数,实现上面的步骤,将结果Pager对象存成一个属性,jsp中可以使用。同时存入查询条件,方便下页等标签使用。
- (V)Jsp界面中可以通过EL表达式,取得上一步存入的结果,显示。下一页等标签可以使用js或者url传值,主要是pageNum+1,还有上次查询的条件。点击跳转到servlet,根据同样的查询条件和pageNum,计算新的Pager对象,在jsp显示。
核心代码:
//JdbcUtil.java jdbc工具包,有查询、更新、释放
package com.xf.page.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author XF * JDBC工具类 */ public class JdbcUtil { private static String USERNAME; private static String PASSWORD; private static String DRIVER; private static String URL; private Connection connection; private PreparedStatement pstmt; private ResultSet resultSet; static{ loadConfig(); } /** * 加载数据库配置信息,并给相关的属性赋值 */ public static void loadConfig(){ USERNAME = "root"; PASSWORD = "root"; DRIVER = "com.mysql.jdbc.Driver"; URL = "jdbc:mysql://localhost:3306/page"; //根据项目选择dataBase } public JdbcUtil() { } public Connection getConnection() { try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { throw new RuntimeException("get connection error!"); } return connection; } /** * 执行更新操作 * @param sql sql语句 * @param params 执行参数 * @return 执行结果 * @throws SQLException */ public boolean updateByPreparedStatement(String sql, List<?> params) throws SQLException { boolean flag = false; int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数 pstmt = connection.prepareStatement(sql); int index = 1; // 填充sql语句中的占位符 if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } result = pstmt.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 执行查询操作 * @param sql sql语句 * @param params 执行参数 * @return * @throws SQLException */ public List<Map<String, Object>> findResult(String sql, List<?> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } list.add(map); } return list; } /** * 释放资源 */ public void releaseConn() { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
//SublistStudentDaoImpl.java 查询满足条件的对象,并传入参数,生成Pager对象,即结果
package com.xf.page.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.xf.page.model.Pager; import com.xf.page.model.Student; import com.xf.page.util.JdbcUtil; public class SublistStudentDaoImpl implements StudentDao { //调用方法getAllStudent,然后根据传入的参数,生成Pager对象,即结果。 @Override public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) { // TODO Auto-generated method stub List<Student> allStudents = getAllStudent(searchModel); Pager<Student > pager = new Pager<Student>(pageNum, pageSize, allStudents); System.out.println("DaoImpl: pageNum= "+pageNum); return pager; } //查找所有满足条件的对象 private List<Student> getAllStudent(Student searchModel){ List<Student> result = new ArrayList<Student>(); List<Object> paramList = new ArrayList<Object>(); String stuName = searchModel.getName(); // System.out.println("impl : name: "+stuName); int gender = searchModel.getGender(); StringBuilder sql = new StringBuilder("select * from t_student where 1=1"); if(stuName != null && !stuName.equals("")){ sql.append(" and stu_name like ?"); paramList.add("%"+stuName+"%"); } if(gender == Constant.GENDER_FEMALE || gender == Constant.GENDER_MALE){ sql.append(" and gender = ?"); paramList.add(gender); } JdbcUtil jdbcUtil = null; try { jdbcUtil = new JdbcUtil(); jdbcUtil.getConnection(); List<Map<String, Object>> mapList = jdbcUtil.findResult(sql.toString(), paramList); if(mapList != null){ for(Map<String, Object> map:mapList){ Student s = new Student(map); // System.out.println("name: "+s.getName()); result.add(s); } } } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException("查询所有数据异常!",e); }finally{ if(jdbcUtil != null){ jdbcUtil.releaseConn(); } } return result; } }
</pre><pre name="code" class="java">//Pager.java <span style="font-family: Arial, Helvetica, sans-serif;">根据传入参数实例化Pager对象,计算相应的信息</span>
package com.xf.page.model; import java.io.Serializable; import java.util.List; public class Pager<T> implements Serializable { /** * */ private static final long serialVersionUID = -1380898667849848066L; private int pageSize; private int currentPage; private int totalRecord;//一共多少条记录 private int totalPage; private List<T> dataList; //根据传入参数实例化Pager对象,计算相应的信息以及结果dataList public Pager(int pageNum, int pageSize, List<T> sourceList){ if(sourceList == null) return; this.totalRecord = sourceList.size(); this.pageSize = pageSize; this.totalPage = this.totalRecord / this.pageSize; //非整除+1 if(this.totalRecord % this.pageSize != 0) this.totalPage +=1; //当前第几页,大于总页数则赋值为总页数,小于1则赋值为1 if(this.totalPage < pageNum){ this.currentPage = this.totalPage; }else{ this.currentPage = pageNum; } if(this.currentPage < 1) this.currentPage =1; int fromIndex = this.pageSize * (this.currentPage -1); int toIndex = this.pageSize * this.currentPage > this.totalRecord? this.totalRecord: this.pageSize * this.currentPage; this.dataList = sourceList.subList(fromIndex, toIndex); } public Pager() { super(); } public Pager(int pageSize, int currentPage, int totalRecord, int totalPage, List<T> dataList) { super(); this.pageSize = pageSize; this.currentPage = currentPage; this.totalRecord = totalRecord; this.totalPage = totalPage; this.dataList = dataList; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalRecord() { return totalRecord; } public void setTotalRecord(int totalRecord) { this.totalRecord = totalRecord; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } public static long getSerialversionuid() { return serialVersionUID; } }
//SublistServlet.java
package com.xf.page.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xf.page.dao.Constant; import com.xf.page.model.Pager; import com.xf.page.model.Student; import com.xf.page.service.StudentService; import com.xf.page.service.SublistStudentServiceImpl; public class SublistServlet extends HttpServlet { /** * */ private static final long serialVersionUID = -5459092412782251847L; private StudentService studentService = new SublistStudentServiceImpl(); /** * 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 { doPost(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 req, HttpServletResponse res) throws ServletException, IOException { //请求中含有中文,讲req编码设置为utf-8 req.setCharacterEncoding("utf-8"); //接受request参数,先赋值为默认值,避免为null,发生error String name = req.getParameter("name"); System.out.println("servlet : name: "+name); // int gender = Constant.DEFAULT_GENDER; String genderStr = req.getParameter("gender"); if(genderStr != null && !("".equals(genderStr.trim()))){ gender = Integer.parseInt(genderStr); } // int pageNum = Constant.DEFAULT_PAGE_NUM; String pageNumStr = req.getParameter("pageNum"); if(pageNumStr != null && !("".equals(pageNumStr.trim()))){ pageNum = Integer.parseInt(pageNumStr); } // int pageSize = Constant.DEFAULT_PAGE_SIZE; String pageSizeStr = req.getParameter("pageSize"); if(pageSizeStr != null && !("".equals(pageSizeStr.trim()))){ pageSize = Integer.parseInt(pageSizeStr); } //组装查询条件 Student searchModel = new Student(); searchModel.setName(name); searchModel.setGender(gender); //查询结果 Pager<Student> result = studentService.findStudent(searchModel, pageNum, pageSize); //存储返回的结果 req.setAttribute("result", result); //存储查询信息,为下页,上页等标签保留查询信息 req.setAttribute("name", name); req.setAttribute("gender", gender); req.getRequestDispatcher("/sublistStudent.jsp").forward(req, res); } }
//sublistStudent.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>学生信息</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> </style> <% String context = request.getContextPath(); %> </head> <body> <h2>学生信息</h2> <div> <form action="<%=context%>/servlet/sublistServlet" id= "stuForm" method="post"> 姓名 <input type='text' name="name" id="name" > 性别 <select name="gender" id="gender"> <option value="-1">全部</option> <option value="1">男</option> <option value="2">女</option> </select> <input type="submit" value="查询"> </form> </div> <div> 学生信息列表:<br><br> <!-- 后台返回结果为空 --> <c:if test="${fn:length(result.dataList) eq 0 }"> <span>查询结果不存在</span> </c:if> <!-- 后台返回结果不为空 --> <c:if test="${fn:length(result.dataList) gt 0}"> <table border= 1px;> <tr height="30" > <th width="130">姓名</th> <th width="130">性别</th> <th width="130">年龄</th> <th width="230">家庭住址</th> </tr> <c:forEach items="${result.dataList }" var="student"> <tr> <td><c:out value="${student.name }"></c:out></td> <td> <c:if test="${student.gender eq 1 }">男</c:if> <c:if test="${student.gender eq 2 }">女</c:if> </td> <td><c:out value="${student.age }"></c:out></td> <td><c:out value="${student.address }"></c:out></td> </tr> </c:forEach> </table><br> 共${result.totalRecord }条记录,共${result.totalPage }页,当前第${result.currentPage}页 <a href="servlet/sublistServlet?pageNum=1&name=${name}&gender=${gender}" >首页</a> <!-- 这类标签必须带有查询信息 --> <a href="servlet/sublistServlet?pageNum=${result.currentPage+1 }&name=${name}&gender=${gender}" >下一页</a> <a href="servlet/sublistServlet?pageNum=${result.currentPage-1 }&name=${name}&gender=${gender}" >上一页</a> <a href="servlet/sublistServlet?pageNum=${result.totalPage }&name=${name}&gender=${gender}" >尾页</a> </c:if> </div> </body> </html>