在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;" >當前位置:統計報表&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的映射

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM