在实现分页的时候,我使用的是数据库下面的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;" >当前位置:统计报表&nbsp;&gt;&nbsp;客户构成分析
<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 %>条记录&nbsp;每页2条&nbsp;
<a href="getUser?page=<%=1 %>" title="首页">&laquo;首页</a>
<a href="getUser?page=<%=p-1 %> " title="上一页">&laquo; 上一页</a>
<a href="getUser?page=<%=p+1 %>" title="下一页">下一页&raquo;</a>
<a href="getUser?page=<%=totePage %>" title="末页">末页&raquo;</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项目中实现分页效果的更多相关文章

  1. MVC项目中的分页实现例子

    在开发项目中,写了一个分页实现的例子,现在把源代码贴上,以供以后写代码时参考 在列表的头部,有如下显示, 这个代表一个页面显示10条记录,总共22条记录. 这个是页面底部的显示 那么如何来显示这个分页 ...

  2. jqPaginator 项目中做分页的应用技巧

    最近做后台管理系统,分页用到的不少,项目中其实已经有分页功能的组件但是不够高度自定义,于是就找到了 jqPaginator 高度自定义的Html结构 初始化引用如下: $("#paginat ...

  3. simple高度自定义的jqPaginator 项目中做分页的应用技巧

    最近做后台管理系统,分页用到的不少,项目中其实已经有分页功能的组件但是不够高度自定义,于是就找到了 jqPaginator 高度自定义的Html结构 初始化引用如下: $("#paginat ...

  4. 项目中DataTables分页插件的使用

    在项目开发的过程中,一般都会对表格进行分页处理,大多是情况下会在项目中配置好后台分页插件,提高效率,减轻浏览器的压力.但是有时会遇到有些数据不能直接通过分页插件操作数据库进行分页数据查询,那就需要用到 ...

  5. SSH 项目中 用Hibernate底层 简单的封装DAO层

    废话不多少了,主要是使用hibernate的查询方法,自己封装了DAO层,供service来方便使用. 首先:必须要继承的 public class CommonDao extends Hiberna ...

  6. ElementUi中el-table分页效果

    现实的场景中很经常遇到表格el-table数据过多,为了更好的用户体验,所以我们需要用到分页,一般分页可以视数据量的大小可分为前端控制和后端控制. 先看下效果(已做脱敏处理) 图1 前端el-tabl ...

  7. ssh框架中的分页查询

    ssh中的分页查询是比较常用的,接下来我用代码来介绍如何实现一个分页查询 首先建立一个Model用来储存查询分页的信息 package com.haiziwang.qrlogin.utils; imp ...

  8. hessian在ssh项目中的配置

    一. 在服务端发布一个web项目 1.创建一个动态的web项目,并导入hessian的jar包 2. 在服务端的crm项目中创建接口 package cn.rodge.crm.service;impo ...

  9. SSH 项目中 使用websocket 实现网页聊天功能

    参考文章  :java使用websocket,并且获取HttpSession,源码分析    http://www.cnblogs.com/zhuxiaojie/p/6238826.html 1.在项 ...

随机推荐

  1. mysql源码编译安装

    首先去官网http://dev.mysql.com/downloads/mysql/ 下载mysql源码.我下的是5.7.10 源码选择的是 Generic Linux (Architecture I ...

  2. cookie、session、sessionid ,jsessionid 的区别

    本文是转载虫师博客的文章http://www.cnblogs.com/fnng/archive/2012/08/14/2637279.html cookie.session.sessionid 与js ...

  3. python16_day39【算法】

    复习: 1.递归 调用自身 结束条件 一.冒泡算法 def bubble_sort(numbs): for i in range(len(numbs)-1): # 这个循环负责设置冒泡排序进行的次数. ...

  4. eclipse导入Java源码

    eclipse导入Java源码 下载源码包(一般jdk都自带了, 我的没有) src.zip eclipse -> window -> preferences -> JAVA -&g ...

  5. C++语言中的四种类型转换

    1 引子 这篇笔记是根据StackOverflow上面的一个问题整理而成,主要内容是对C/C++当中四种类型转换操作进行举例说明.在之前其实对它们都是有所了解的,而随着自己在进行总结,并敲了一些测试示 ...

  6. RabittMQ实践(一): RabbitMQ的安装、启动

    安装:   启动监控管理器:rabbitmq-plugins enable rabbitmq_management 关闭监控管理器:rabbitmq-plugins disable rabbitmq_ ...

  7. PHP开发之thinkPHP分层设计

    thinkphp模型层Model.Logic.Service讲解        ThinkPHP支持模型的分层 ,除了Model层之外,我们可以项目的需要设计和创建其他的模型层. 通常情况下,不同的分 ...

  8. TED #05# How we can face the future without fear, together

    Rabbi Lord Jonathan Sacks: How we can face the future without fear, together 1. what was it like bei ...

  9. CSS3 Flex Box(弹性盒子)

    CSS3 Flex Box(弹性盒子) 一.简介 弹性盒子是 CSS3 的一种新的布局模式. CSS3 弹性盒( Flexible Box 或 flexbox),是一种当页面需要适应不同的屏幕大小以及 ...

  10. Python3.6(windows系统)通过pip安装bs4

    Python3.6(windows系统)通过pip安装bs4 cmd安装命令: pip install beautifulsoup4 执行结果: