在ssh项目中实现分页效果

注定要成为攻城狮的男人 注定要成为攻城狮的男人     2022-09-07     572

关键词:

在实现分页的时候,我使用的是数据库下面的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的映射

 

 

 

如何使用hibernate在spring boot中实现分页

...:我正在使用带有休眠功能的SpringBoot,并且我想在我的项目中使用分页。我在谷歌上搜索并看到了很多例子,但我无法在我的项目中实现它。我希望如果我在我的url中传递1,那么应该有10个结果,如果我传递2 查看详情

如何在Android listview中实现分页

...:我正在为Android应用程序工作,我需要在其中显示带有项目的列表视图。但是列表视图中要显示更多元素。我决定实现分页。我尝试在Google中搜索,但没有找到任何相关信息。谁能帮帮我..【问题讨论】:什么样的导航?您可以... 查看详情

如何在 Xamarin 表单中实现分页

】如何在Xamarin表单中实现分页【英文标题】:HowtoachievePaginationinXamarinforms【发布时间】:2021-12-2613:42:06【问题描述】:我需要在列表视图页面中实现分页。在这里,我在一个表中显示成百上千条记录,因此需要分页功能。由于... 查看详情

如何在nodejs + postgresql中实现分页

】如何在nodejs+postgresql中实现分页【英文标题】:Howtoimplementpaginationinnodejs+postgresql【发布时间】:2018-06-2604:23:58【问题描述】:我是Node.js的新手。我想在Node.js中使用express作为框架和Postgresql作为数据库在我的Api编写中实现分页... 查看详情

在mongodb中实现分页

】在mongodb中实现分页【英文标题】:Implementingpaginationinmongodb【发布时间】:2015-03-2204:52:34【问题描述】:我知道使用skip来实现分页是一种不好的做法,因为当您的数据变大时skip开始消耗大量内存。解决此问题的一种方法是使... 查看详情

如何在排名查询中实现分页?

】如何在排名查询中实现分页?【英文标题】:Howtoimplementpaginginrankingquery?【发布时间】:2014-03-0506:18:32【问题描述】:我正在尝试使用MySQL进行排名。我找到了一篇关于它的好文章,没有使用自连接(rankingwithoutselfjoin)。SELECTscore... 查看详情

如何在 dojox.datagrid 中实现分页

】如何在dojox.datagrid中实现分页【英文标题】:howtoimplementpaginationindojox.datagrid【发布时间】:2019-02-1319:37:34【问题描述】:我有一个在dojox.datagrid中显示分页的请求,我尝试搜索但没有运气。想知道dojox.datagrid中是否可以分页,... 查看详情

java示例代码_在Spring MVC 3中实现分页

java示例代码_在Spring MVC 3中实现分页 查看详情

如何在 React 中实现分页

】如何在React中实现分页【英文标题】:HowtoimplementpaginationinReact【发布时间】:2017-03-0701:58:48【问题描述】:我是ReactJS的新手,正在其中创建一个简单的TODO应用程序。实际上,它是一个非常基本的应用程序,没有数据库连接,... 查看详情

如何在 Git 标签中实现分页

】如何在Git标签中实现分页【英文标题】:HowtoachievepaginationinGittag【发布时间】:2021-11-0519:04:31【问题描述】:谁帮帮我将git标签限制为100需要在第一次获取时获取前100个标签需要传递一些key或token来获取下一批可以像分页一样... 查看详情

使用 scrollViewDidScroll 方法在 UITableView 中实现分页?

】使用scrollViewDidScroll方法在UITableView中实现分页?【英文标题】:ImplementingpaginationinUITableViewwithscrollViewDidScrollmethod?【发布时间】:2014-09-1714:59:06【问题描述】:我正在构建一个文章阅读应用程序。我正在使用AFNetworking第三方库... 查看详情

如何在 PHP 中实现分页? [关闭]

】如何在PHP中实现分页?[关闭]【英文标题】:HowdoyouimplementpaginationinPHP?[closed]【发布时间】:2010-09-2100:57:37【问题描述】:PHP中通常如何实现分页结果?我想要一个包含10个结果的结果页面。在导航中向前翻页会给我下一组和上... 查看详情

如何在 Spring MVC 3 中实现分页 [关闭]

】如何在SpringMVC3中实现分页[关闭]【英文标题】:HowtoimplementpaginationinSpringMVC3[closed]【发布时间】:2011-01-1517:54:46【问题描述】:是否有任何开箱即用、易于实现的标准分页组件/标签库或代码示例可用于SpringMVC中的分页?【问题... 查看详情

如何在 SQL for MS Access 中实现分页?

】如何在SQLforMSAccess中实现分页?【英文标题】:HowdoIimplementpaginationinSQLforMSAccess?【发布时间】:2009-12-1412:25:24【问题描述】:我正在使用ASP.NET通过OdbcConnection类访问MicrosoftAccess2002数据库(MDB),虽然速度很慢,但它运行良好。我... 查看详情

在 ASP.NET Core 2.1 Web API 中实现分页

】在ASP.NETCore2.1WebAPI中实现分页【英文标题】:ImplementPaginationinASP.NETCore2.1WebAPI【发布时间】:2019-02-1905:28:50【问题描述】:我搜索了,但并没有真正找到关于如何在ASP.NETWebAPICore2.1应用程序中实现分页逻辑的文章...我有以下[Route... 查看详情

如何在 SQL for MS Access 中实现分页?

】如何在SQLforMSAccess中实现分页?【英文标题】:HowdoIimplementpaginationinSQLforMSAccess?【发布时间】:2009-12-1412:25:24【问题描述】:我正在使用ASP.NET通过OdbcConnection类访问MicrosoftAccess2002数据库(MDB),虽然速度很慢,但它运行良好。我... 查看详情

在unity中实现分页扩展(旋转3d)功能(ugui)(代码片段)

这次给大家介绍一个看起来是3D的效果的UI的切换在实际应用中别看起来不是那么呆板我们要首先创建两个Image通过修改point的位置来改变旋转的轴我们可以看到有两个模块是两个不同的方向的旋转我们分别把两块的pivot分别设为&#... 查看详情

如何在后端自定义查询中实现分页

】如何在后端自定义查询中实现分页【英文标题】:Howtoimplementpaginationincustomqueryinbackand【发布时间】:2016-02-2319:31:05【问题描述】:我想在我的自定义查询中实现分页,就像在提供的查询中一样。我想提供行数和页数。我尝试... 查看详情