Java分页技术的实现(一)

来源:互联网 发布:删除sql字段数据 编辑:程序博客网 时间:2024/06/05 15:33

(一)创建一个web项目

这里写图片描述


(二)编写Java类
1.建立一个com.imooc.page包

package com.imooc.page;public class Constant {    /**     * 男性     */    public static final int GENDER_MALE = 1;    /**     * 女性     */    public static final int GENDER_FEMALE = 2;    /**     * 默认每页显示多少条记录     */    public static final int DEFAULT_PAGE_SIZE = 5;    /**     * 默认显示第几页记录     */    public static final int DEFAULT_PAGE_NUM = 1;    /**     * 默认学生性别     */    public static final int DEFAULT_GENDER = 0;}///////////////////////////////////////////////////////////package com.imooc.page;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class EncodingFilter implements Filter {    @Override    public void destroy() {        // TODO Auto-generated method stub    }    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        request.setCharacterEncoding("UTF-8");        response.setCharacterEncoding("UTF-8");        chain.doFilter(request,response);    }    @Override    public void init(FilterConfig arg0) throws ServletException {        // TODO Auto-generated method stub    }}

2.创建一个com.imooc.page,model

package com.imooc.page.model;import java.io.Serializable;import java.util.List;public class Pager<T> implements Serializable {    private static final long serialVersionUID = -8741766802354222579L;    private int pageSize; // 每页显示多少条记录    private int currentPage; //当前第几页数据    private int totalRecord; // 一共多少条记录    private int totalPage; // 一共多少页记录    private List<T> dataList; //要显示的数据    public Pager(int pageNum, int pageSize, List<T> sourceList){        if(sourceList == null || sourceList.isEmpty()){            return;        }        // 总记录条数        this.totalRecord = sourceList.size();        // 每页显示多少条记录        this.pageSize = pageSize;        //获取总页数        this.totalPage = this.totalRecord / this.pageSize;        if(this.totalRecord % this.pageSize !=0){            this.totalPage = this.totalPage + 1;        }        // 当前第几页数据        this.currentPage = this.totalPage < pageNum ?  this.totalPage : pageNum;        // 起始索引        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(){    }    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;    }}//////////////////////////////////////////////////////////package com.imooc.page.model;import java.io.Serializable;import java.util.Map;public class Student implements Serializable {    private static final long serialVersionUID = -7476381137287496245L;    private int id; //学生记录id    private String stuName;//学生姓名    private int age; //学生年龄    private int gender; //学生性别    private String address;//学生住址    public Student() {        super();    }    public Student(int id, String stuName, int age, int gender, String address) {        super();        this.id = id;        this.stuName = stuName;        this.age = age;        this.gender = gender;        this.address = address;    }    public Student(Map<String, Object> map){        this.id = (int)map.get("id");        this.stuName = (String)map.get("stu_name");        this.age = (int)map.get("age");        this.gender = (int)map.get("gender");        this.address = (String)map.get("address");    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getStuName() {        return stuName;    }    public void setStuName(String stuName) {        this.stuName = stuName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public int getGender() {        return gender;    }    public void setGender(int gender) {        this.gender = gender;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    @Override    public String toString() {        return "Student [id=" + id + ", stuName=" + stuName + ", age=" + age                + ", gender=" + gender + ", address=" + address + "]";    }}

3.创建一个com.imooc.page.dao包

package com.imooc.page.dao;import com.imooc.page.model.Pager;import com.imooc.page.model.Student;public interface StudentDao {    /**     * 根据查询条件,查询学生分页信息     *      * @param searchModel     *            封装查询条件     * @param pageNum     *            查询第几页数据     * @param pageSize     *            每页显示多少条记录     * @return 查询结果     */    public Pager<Student> findStudent(Student searchModel, int pageNum,            int pageSize);}//////////////////////////////////////////////////////////////////package com.imooc.page.dao;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Map;import com.imooc.page.Constant;import com.imooc.page.model.Pager;import com.imooc.page.model.Student;import com.imooc.page.util.JdbcUtil;public class SublistStudentDaoImpl implements StudentDao {    @Override    public Pager<Student> findStudent(Student searchModel, int pageNum,            int pageSize) {        List<Student> allStudenList = getAllStudent(searchModel);        Pager<Student> pager = new Pager<Student>(pageNum, pageSize,                allStudenList);        return pager;    }    /**     * 模仿获取所有数据     *      * @param searchModel     *            查询参数     * @return 查询结果     */    private static List<Student> getAllStudent(Student searchModel) {        List<Student> result = new ArrayList<Student>();        List<Object> paramList = new ArrayList<Object>();        String stuName = searchModel.getStuName();        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);                    result.add(s);                }            }        } catch (SQLException e) {            throw new RuntimeException("查询所有数据异常!", e);        } finally {            if (jdbcUtil != null) {                jdbcUtil.releaseConn(); // 一定要释放资源            }        }        return result;    }    public static void main(String[] args) {        List<Student> lst = getAllStudent(new Student());        for (Student s : lst) {            System.out.println(s);        }    }}

4.创建一个com.imooc.page.service包

package com.imooc.page.service;import com.imooc.page.model.Pager;import com.imooc.page.model.Student;public interface StudentService {    /**     * 根据查询条件,查询学生分页信息     *      * @param searchModel     *            封装查询条件     * @param pageNum     *            查询第几页数据     * @param pageSize     *            每页显示多少条记录     * @return 查询结果     */    public Pager<Student> findStudent(Student searchModel, int pageNum,            int pageSize);}////////////////////////////////////////////////////////////////package com.imooc.page.service;import com.imooc.page.dao.StudentDao;import com.imooc.page.dao.SublistStudentDaoImpl;import com.imooc.page.model.Pager;import com.imooc.page.model.Student;public class SublistStudentServiceImpl implements StudentService {    private StudentDao studentDao;    public SublistStudentServiceImpl() {        // 创建servivce实现类时,初始化dao对象。        studentDao = new SublistStudentDaoImpl();    }    @Override    public Pager<Student> findStudent(Student searchModel, int pageNum,            int pageSize) {        Pager<Student> result = studentDao.findStudent(searchModel, pageNum,                pageSize);        return result;    }    public StudentDao getStudentDao() {        return studentDao;    }    public void setStudentDao(StudentDao studentDao) {        this.studentDao = studentDao;    }}

5.创建一个com.imooc.page.servlet包

package com.imooc.page.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.imooc.page.Constant;import com.imooc.page.model.Pager;import com.imooc.page.model.Student;import com.imooc.page.service.StudentService;import com.imooc.page.service.SublistStudentServiceImpl;import com.imooc.page.util.StringUtil;public class SublistServlet extends HttpServlet {    private static final long serialVersionUID = -3658128508633145268L;    private StudentService studentService = new SublistStudentServiceImpl();    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 接收request里的参数        String stuName = request.getParameter("stuName"); //学生姓名        // 获取学生性别        int gender = Constant.DEFAULT_GENDER;        String genderStr = request.getParameter("gender");        if(genderStr!=null && !"".equals(genderStr.trim())){            gender = Integer.parseInt(genderStr);        }        // 校验pageNum参数输入合法性        String pageNumStr = request.getParameter("pageNum");         if(pageNumStr !=null && !StringUtil.isNum(pageNumStr)){            request.setAttribute("errorMsg", "参数传输错误");            request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);            return;        }        int pageNum = Constant.DEFAULT_PAGE_NUM; //显示第几页数据        if(pageNumStr!=null && !"".equals(pageNumStr.trim())){            pageNum = Integer.parseInt(pageNumStr);        }        int pageSize = Constant.DEFAULT_PAGE_SIZE;  // 每页显示多少条记录        String pageSizeStr = request.getParameter("pageSize");        if(pageSizeStr!=null && !"".equals(pageSizeStr.trim())){            pageSize = Integer.parseInt(pageSizeStr);        }        // 组装查询条件        Student searchModel = new Student();         searchModel.setStuName(stuName);        searchModel.setGender(gender);        //调用service 获取查询结果        Pager<Student> result = studentService.findStudent(searchModel,                                                                 pageNum, pageSize);        // 返回结果到页面        request.setAttribute("result", result);        request.setAttribute("stuName", stuName);        request.setAttribute("gender", gender);        request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);    }}

6.创建一个com.imooc.page.Util包

package com.imooc.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;public class JdbcUtil {    // 表示定义数据库的用户名    private static String USERNAME ;    // 定义数据库的密码    private static String PASSWORD;    // 定义数据库的驱动信息    private static String DRIVER;    // 定义访问数据库的地址    private static String URL;    // 定义数据库的链接    private Connection connection;    // 定义sql语句的执行对象    private PreparedStatement pstmt;    // 定义查询返回的结果集合    private ResultSet resultSet;    static{        //加载数据库配置信息,并给相关的属性赋值        loadConfig();    }    /**     * 加载数据库配置信息,并给相关的属性赋值     */    public static void loadConfig() {        try {            InputStream inStream = JdbcUtil.class                    .getResourceAsStream("/jdbc.properties");            Properties prop = new Properties();            prop.load(inStream);            USERNAME = prop.getProperty("jdbc.username");            PASSWORD = prop.getProperty("jdbc.password");            DRIVER= prop.getProperty("jdbc.driver");            URL = prop.getProperty("jdbc.url");        } catch (Exception e) {            throw new RuntimeException("读取数据库配置文件异常!", e);        }    }    public JdbcUtil() {    }    /**     * 获取数据库连接     *      * @return 数据库连接     */    public Connection getConnection() {        try {            Class.forName(DRIVER); // 注册驱动            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); // 获取连接        } catch (Exception e) {            throw new RuntimeException("get connection error!", e);        }        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();            }        }    }    public static void main(String[] args) {        JdbcUtil jdbcUtil = new JdbcUtil();        jdbcUtil.getConnection();        try {            List<Map<String, Object>> result = jdbcUtil.findResult(                    "select * from t_student", null);            for (Map<String, Object> m : result) {                System.out.println(m);            }        } catch (SQLException e) {            e.printStackTrace();        } finally {            jdbcUtil.releaseConn();        }    }}//////////////////////////////////////////////////////////////package com.imooc.page.util;import java.util.regex.Matcher;import java.util.regex.Pattern;public class StringUtil {    /**     * 校验字符串是否是大于0的数字     * @param string     * @return     */    public static boolean isNum(String string){        Pattern pattern = Pattern.compile("[1-9]{1}\\d*");        Matcher matcher = pattern.matcher(string);        return matcher.matches();    }}

(三)在page项目文件夹下创建一个config文件夹,在config文件夹下创建jdbc.properties文件。

jdbc.username=rootjdbc.password=rootjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/imooc

(四)在WebContext文件夹下创建sublist文件夹,在sublist文件夹下创建jsp页面。

<%@ 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"><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>学生信息</title></head><%    // 获取请求的上下文    String context = request.getContextPath();%><script type="text/javascript">// 当前第几页数据var currentPage = ${result.currentPage};// 总页数var totalPage = ${result.totalPage};function submitForm(actionUrl){    var formElement = document.getElementById("stuForm");    formElement.action = actionUrl;    formElement.submit();}// 第一页function firstPage(){    if(currentPage == 1){        alert("已经是第一页数据");        return false;    }else{        submitForm("<%=context %>/sublist/SublistServlet?pageNum=1");        return true;    }}// 下一页function nextPage(){    if(currentPage == totalPage){        alert("已经是最后一页数据");        return false;    }else{        submitForm("<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage+1));        return true;    }}// 上一页function previousPage(){    if(currentPage == 1){        alert("已经是第一页数据");        return false;    }else{        submitForm("<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage-1));        return true;    }}// 尾页function lastPage(){    if(currentPage == totalPage){        alert("已经是最后一页数据");        return false;    }else{        submitForm("<%=context %>/sublist/SublistServlet?pageNum=${result.totalPage}");        return true;    }}function initPage(){    var genderRequest = "${gender}" ;    var genderVal = 0;    var genderElement = document.getElementById("gender");    if(genderRequest != ""){        genderVal = parseInt(genderRequest);    }    var options = genderElement.options;    var i = 0;    for(i = 0; i < options.length; i++){        if(options[i].value == genderVal){            options[i].selected=true;            break;        }    }}</script><body onload="initPage();">    <div style="margin-left: 100px; margin-top: 100px;">        <div>            <font color="red">${errorMsg }</font>        </div>        <div>            <form action="<%=context %>/sublist/SublistServlet"   id="stuForm"  method="post">                姓名                <input type="text" name="stuName" id="stu_name" style="width:120px" value="${stuName }">                &nbsp;                性别                <select name="gender" id="gender" style="width:80px">                    <option value="0">全部</option>                    <option value="1"></option>                    <option value="2"></option>                </select>                &nbsp;&nbsp;                <input type="submit" value="查询">            </form>        </div>              <br>        学生信息列表:<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" cellspacing="0px"                style="border-collapse: collapse">                <thead>                    <tr height="30">                        <th width="130">姓名</th>                        <th width="130">性别</th>                        <th width="130">年龄</th>                        <th width="190">家庭地址</th>                    </tr>                </thead>                    <c:forEach items="${result.dataList }" var="student">                        <tr>                            <td><c:out value="${student.stuName }"></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 }页&nbsp;&nbsp;当前第${result.currentPage }页&nbsp;&nbsp;            <a href="#" onclick="firstPage();">首页</a>&nbsp;&nbsp;             <a href="#" onclick="nextPage();">下一页</a>&nbsp;&nbsp;             <a href="#" onclick="previousPage();">上一页</a>&nbsp;&nbsp;            <a href="#" onblur="lastPage();">尾页</a>         </c:if>    </div></body></html>

(五)在WEB-INF文件夹下创建一个lib文件夹导入相关jar包。

(六)在WEB-INF文件夹下创建一个web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    id="WebApp_ID" version="3.0">    <display-name>pager</display-name>    <filter>        <filter-name>EncodingFilter</filter-name>        <filter-class>com.imooc.page.EncodingFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>EncodingFilter</filter-name>        <url-pattern>*</url-pattern>    </filter-mapping>  <servlet>    <servlet-name>SublistServlet</servlet-name>    <servlet-class>com.imooc.page.servlet.SublistServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>SublistServlet</servlet-name>    <url-pattern>/sublist/SublistServlet</url-pattern>  </servlet-mapping>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>

(七)创建数据库

CREATE TABLE `t_student` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `stu_name` varchar(16) NOT NULL,  `gender` int(11) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `address` varchar(128) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;-- Records of t_student-- ----------------------------INSERT INTO `t_student` VALUES ('1', '王小军', '1', '17', '北京市东城区');INSERT INTO `t_student` VALUES ('2', '李雷雷', '1', '16', '北京市朝阳区');INSERT INTO `t_student` VALUES ('3', '张静', '2', '16', '北京市昌平区');INSERT INTO `t_student` VALUES ('4', '王晓萌', '2', '17', '北京市顺义区');INSERT INTO `t_student` VALUES ('5', '韩梅梅', '2', '16', '北京市朝阳区');INSERT INTO `t_student` VALUES ('6', '李小军', '1', '17', '北京市海淀区');INSERT INTO `t_student` VALUES ('7', '成龙', '1', '16', '北京市石景山区');INSERT INTO `t_student` VALUES ('8', '李海飞', '2', '16', '北京市海淀区');INSERT INTO `t_student` VALUES ('9', '罗红', '2', '16', '北京市朝阳区');INSERT INTO `t_student` VALUES ('10', '孙海杰', '1', '16', '北京市石景山区');INSERT INTO `t_student` VALUES ('11', '王海龙', '1', '16', '北京市东城区');

(八)演示结果

这里写图片描述


这里写图片描述

原创粉丝点击