首页 > 代码库 > 在SSH项目中实现分页效果
在SSH项目中实现分页效果
在实现分页的时候,我使用的是数据库下面的User表,实现的效果是通过分页查询
能够将表中的数据分页显示,点击相关的按钮实现:首页、上一页、下一页、末页的显示
1新建一个dynamic web project项目 ,导入SSH项目所需要的jar
antlr-2.7.7.jar
c3p0-0.9.5.2.jar
classmate-1.3.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.commons.pool-1.5.3.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-fileupload-1.3.2.jar
commons-io-2.4.jar
commons-lang3-3.4.jar
dom4j-1.6.1.jar
freemarker-2.3.23.jar
hibernate-c3p0-5.2.10.Final.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.10.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.3.Final.jar
javassist-3.20.0-GA.jar
jboss-logging-3.3.0.Final.jar
jboss-transaction-api_1.2_spec-1.0.1.Final.jar
jstl.jar
log4j-api-2.7.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.24-bin.jar
mysql-connector-java-5.1.7-bin.jar
ognl-3.1.12.jar
spring-aop-4.3.6.RELEASE.jar
spring-aspects-4.3.6.RELEASE.jar
spring-beans-4.3.6.RELEASE.jar
spring-context-4.3.6.RELEASE.jar
spring-core-4.3.6.RELEASE.jar
spring-expression-4.3.6.RELEASE.jar
spring-jdbc-4.3.6.RELEASE.jar
spring-orm-4.3.6.RELEASE.jar
spring-tx-4.3.6.RELEASE.jar
spring-web-4.3.6.RELEASE.jar
standard.jar
struts2-core-2.5.10.1.jar
struts2-spring-plugin-2.5.10.1.jar
2 在web.xml下配置Struts的过滤器<context-param>和<listener>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>PagePractice</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>Struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>Struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
3 按照SSH项目的套路,建立相关的类。其中特殊点在于工具类和dao的实现类
工具类代码如下:
package com.whl.utils; import com.whl.bean.Page; public class PageUtils { public static Page getPage(int everyPage, int totalCount, int currentPage) { Page page = null; everyPage = getEveryPage(everyPage); currentPage = getCurrentPage(currentPage); int totalPage = getTotalPage(everyPage, totalCount); int beginIndex = getBeginIndex(everyPage, currentPage); boolean hasPrePage = hasPrePage(currentPage); boolean hasNextPage = hasNextPage(totalPage, currentPage); return page = new Page(everyPage, totalCount, totalPage, currentPage, beginIndex, hasPrePage, hasNextPage); } /** * 设定每一页显示的记录数 * * @param everyPage * @return */ public static int getEveryPage(int everyPage) { return everyPage == 0 ? 3 : everyPage; } /** * 设定当前页 * * @param currentPage * @return */ public static int getCurrentPage(int currentPage) { return currentPage == 0 ? 1 : currentPage; } /** * 设定分页的总页数 * * @param everyPage * @param totalCount * @return */ public static int getTotalPage(int everyPage, int totalCount) { int num = totalCount / getEveryPage(everyPage); return totalCount % getEveryPage(everyPage) == 0 ? num : num + 1; } /** * 设置起始点 * * @param everyPage * @param currentPage * @return */ public static int getBeginIndex(int everyPage, int currentPage) { return (getCurrentPage(currentPage) - 1) * getEveryPage(everyPage); } /** * 设置是否有上一页 * * @param currentPage * @return */ public static boolean hasPrePage(int currentPage) { return getCurrentPage(currentPage) == 1 ? false : true; } /** * 设置是否有下一页 * * @param currentPage * @return */ public static boolean hasNextPage(int totalPage, int currentPage) { return getCurrentPage(currentPage) == totalPage || totalPage == 0 ? false : true; } }
dao的实现类如下:
package com.whl.daoimpl; import java.util.List; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateTemplate; import com.whl.bean.Page; import com.whl.bean.User; import com.whl.dao.IUserDao; import com.whl.utils.PageUtils; public class IUserDaoImpl extends HibernateTemplate implements IUserDao { @Override public List<User> getUserByPage(int currentPage) { List<User> list = null; Session session=getSessionFactory().openSession(); org.hibernate.query.Query<User> query = session.createQuery("select u from User u",User.class); //list=query.getResultList(); int tote=query.list().size(); System.out.println(tote+"kk"); Page page=PageUtils.getPage(2, tote, currentPage); query.setMaxResults(page.getEveryPage()); query.setFirstResult(page.getBeginIndex()); list = query.getResultList(); System.out.println("DDDD"+list); return list; } @Override public List<User> getAllUser() { List<User> list=getSessionFactory().openSession().createCriteria(User.class).list(); return list; } }
展示页面代码如下:
<%@page import="com.whl.bean.User"%> <%@page import="java.util.List"%> <%@ 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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>User page</title> <link href="css/stylesheet.css" rel="stylesheet" type="text/css" /> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/simpla.jquery.configuration.js"></script> <script type="text/javascript" src="js/javascript.js"></script> <script type="text/javascript" src="datepicker/WdatePicker.js"> </script> </head> <body> <div style="padding:5px;"> <div class="txt" style="padding-top:3px;" >当前位置:统计报表 > 客户构成分析 <hr class="hr1" /> </div> <div class="operation_button"> <a href="#" title="查询">查询</a> </div> <div class="search_input"> <ul class="txt"> <li>报表方式: <select> <option>按等级</option> <option>按信用度</option> <option>按满意度</option> </select> </li> </ul> </div> <div> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table_list" > <thead> <tr> <th width="15%">编号</th> <th width="65%">姓名</th> <th width="20%">密码</th> </tr> </thead> <% List<User> list=(List<User>)request.getAttribute("list"); int tote=(Integer)request.getAttribute("tote"); int p=(Integer)request.getAttribute("page"); int totePage=(Integer)request.getAttribute("totalPage"); if(p<=0){ p=1; }if(p>=totePage){ p=totePage-1; } for(int i=0;i<list.size();i++){ User u=list.get(i); %> <tbody> <tr> <td><%=u.getId() %></td> <td><%=u.getUsername() %></td> <td><%=u.getUserpass() %></td> </tr> </tbody> <% } %> </table> </div> <div class="position"> 共<%=tote %>条记录 每页2条 <a href="getUser?page=<%=1 %>" title="首页">«首页</a> <a href="getUser?page=<%=p-1 %> " title="上一页">« 上一页</a> <a href="getUser?page=<%=p+1 %>" title="下一页">下一页»</a> <a href="getUser?page=<%=totePage %>" title="末页">末页»</a> </div> </div> </body> </html>
Struts.xml代码:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="false" /> <package name="myStruts" extends="struts-default" namespace="/"> <action name="getUser" class="getUser" method="getUser"> <result>/list.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts>
applicationContext.xml代码
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> <!--连接池中保留的最小连接数。--> <property name="minPoolSize" value="10" /> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="100" /> <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="1800" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="3" /> <property name="maxStatements" value="1000" /> <property name="initialPoolSize" value="10" /> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod" value="60" /> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="30" /> <property name="breakAfterAcquireFailure" value="true" /> <property name="testConnectionOnCheckout" value="false" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL5InnoDBDialect </prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.whl.bean</value> </list> </property> </bean> <bean id="userDao" class="com.whl.daoimpl.IUserDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userService" class="com.whl.serviceimpl.IUserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <bean id="getUser" class="com.whl.action.UserAction"> <property name="userService" ref="userService"></property> </bean> </beans>
bean包下面的User类和Page类代码:
package com.whl.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column(length=30) private String username; @Column(length=30) private String userpass; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpass() { return userpass; } public void setUserpass(String userpass) { this.userpass = userpass; } public User(int id, String username, String userpass) { super(); this.id = id; this.username = username; this.userpass = userpass; } public User() { super(); } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", userpass=" + userpass + "]"; } }
package com.whl.bean; public class Page { // 1. 每页显示的数量 private int everyPage; // 2. 总条目数 private int totalCount; // 3. 总页数 private int totalPage; // 4. 当前页数 private int currentPage; // 5. 起始页 private int beginIndex; // 6. 是否有上一页 private boolean hasPrePage; // 7. 是否还有下一页 private boolean hasNextPage; public Page() { } public Page(int everyPage, int totalCount, int totalPage, int currentPage, int beginIndex, boolean hasPrePage, boolean hasNextPage) { super(); this.everyPage = everyPage; this.totalCount = totalCount; this.totalPage = totalPage; this.currentPage = currentPage; this.beginIndex = beginIndex; this.hasPrePage = hasPrePage; this.hasNextPage = hasNextPage; } public int getEveryPage() { return everyPage; } public void setEveryPage(int everyPage) { this.everyPage = everyPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getBeginIndex() { return beginIndex; } public void setBeginIndex(int beginIndex) { this.beginIndex = beginIndex; } public boolean isHasPrePage() { return hasPrePage; } public void setHasPrePage(boolean hasPrePage) { this.hasPrePage = hasPrePage; } public boolean isHasNextPage() { return hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } }
action的代码:
package com.whl.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.whl.bean.User; import com.whl.service.IUserService; import com.whl.utils.PageUtils; public class UserAction extends ActionSupport implements ModelDriven<User>{ private User user=new User(); private IUserService userService; public void setUserService(IUserService userService) { this.userService = userService; } @Override public User getModel() { return user; } public String getUser(){ HttpServletRequest request=ServletActionContext.getRequest(); List<User> allUser = userService.getAllUser(); int tote=allUser.size(); int totalPage = PageUtils.getTotalPage(2, tote); System.out.println(request.getParameter("page")); int page=Integer.parseInt(request.getParameter("page")); List<User> list = userService.getUserByPage(page); if (list!=null&&list.size()!=0) { request.setAttribute("totalPage", totalPage); request.setAttribute("page", page); request.setAttribute("tote", tote); request.setAttribute("list", list); System.out.println(list); return SUCCESS; } return INPUT; } }
涉及到相关知识:
c3po的配置:
Spring的依赖注入;
注解实现Hibernate的映射
在SSH项目中实现分页效果