struts2.0 + hibernate + oracle 分页问题

最近弄了下  struts2.0 + hibernate + oracle 分页问题的

从网上搜了些资料。总觉得不是很合心意。自己做了例子。

 ueser.sql

DROP TABLE "SCOTT"."T_USER" cascade constraints;
DROP SEQUENCE "SCOTT"."Q_USER";

CREATE TABLE "SCOTT"."T_USER"
  (
    "ID"       CHAR(4 BYTE) NOT NULL ENABLE,
    "USERNAME" VARCHAR2(20 BYTE) NOT NULL ENABLE,
    "PASSWORD" VARCHAR2(20 BYTE) NOT NULL ENABLE,
    CONSTRAINT "T_USER_PK" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "SYSTEM" ENABLE
  )
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE
  (
    INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT
  )
  TABLESPACE "SYSTEM" ;
  
 
  CREATE SEQUENCE "SCOTT"."Q_USER" MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 START WITH 121 CACHE 20 NOORDER NOCYCLE ;
  
  Insert into T_USER (ID,USERNAME,PASSWORD) values (Q_USER.nextval,'222','222'); 

 HibernateUtil.java

package hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate的工具类.
 * @author AmigoXie
 */
public class HibernateUtil {
    private static SessionFactory sessionFactory;

    /** 持有一个单态的Session实例.  */
    private static final ThreadLocal threadLocal = new ThreadLocal();
    
    /** 持有一个单态的configuration实例.  */
    private static final Configuration cfg = new Configuration();
    private static String CONFIG_FILE_LOCATION = "hibernate/hibernate.cfg.xml";
    
    static {
        try {
            sessionFactory = new Configuration().configure(CONFIG_FILE_LOCATION)
            	.buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 获得当前的Session实例.
     * @return Session
     * @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        //if (session == null) {
        if(session==null||session.isOpen()==false){        	
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%"
                    		+ e.getMessage());
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }

        return session;
    }
}

 User.java

package hibernate;

public class User {
	
	
	private String id ;
	private String userName;
	private String password;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

 hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory> 
		<!-- properties --> 
		<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:JIM</property> 
		<property name="connection.username">scott</property> 
		<property name="connection.password">tiger</property>
		<property name="dialect">org.hibernate.dialect.OracleDialect</property> 
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
		<property name="show_sql">true</property>
		<property name="format_sql">false</property>		 
		<!-- mapping files --> 
		<mapping resource="hibernate/user.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

 user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hibernate">
  <class name="User" table="T_USER">
     
  
    <id name="id" column="ID" type="string">
      <generator class="assigned"/>
    </id>
    <property name="userName"  column="USERNAME"  type="string" not-null="true" />  
    <property name="password"     column="PASSWORD"     type="string" not-null="true" /> 
 </class>

</hibernate-mapping>

  IuserDao.java接口

package page;

import hibernate.User;

import java.util.List;



public interface IuserDao {
	
	public List<User> displayUser(int offset,int max);
	
	public int count();

}

 

UserDao.java

package page;

import hibernate.HibernateUtil;
import hibernate.User;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;



public class UserDao implements IuserDao {

	@Override
	public List<User> displayUser(int offset, int max) {
		// TODO Auto-generated method stub
		
		//PagerModel<User> pm = null;
		List<User> list =null;
		String hsql = "from User ";
		
		Session session = HibernateUtil.currentSession();
		Transaction ts = null;
		try {
			 ts = session.beginTransaction();
			Query query = session.createQuery(hsql);
			
			query.setFirstResult(offset);
			query.setMaxResults(max);
			 list  = query.list();
		
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if (ts != null) {
				ts.rollback();
			}
		}finally{
			session.close();
		}
		
		return list;
		
	}

	@Override
	public int count() {
		// TODO Auto-generated method stub
		int i = 0 ;
		Session session = HibernateUtil.currentSession();
		Transaction ts = null;
		try {
			 ts = session.beginTransaction();
			Query query = session.createQuery("select count(*) from User");
			i = (Integer) query.uniqueResult();
			
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
			if (ts != null) {
				ts.rollback();
			}
			
		}finally{
			session.close();
		}
		
		return i;
		
	}

}

 

pageAction.java

package page;

import java.util.List;

import hibernate.User;

import com.opensymphony.xwork2.ActionSupport;

public class PageAction extends ActionSupport {
	 	int i=1;//中间变量
	    private int k;//储存最大页面数
	    private int pageNow=1; //页码数,初始为1
	    private int pageSize = 5 ; //页面行数 
	    private int intRowCount = 0;//总行数
	    private int intPageCount = 1;//总页数
	  //  private Admin admin;
	  //  private List<Admin> Adminss;
	    private User user;
	   
	    private List<User> users;
	    
	    private int id;
	    private int aid;

	    
	    public User getUser() {
			return user;
		}

		public void setUser(User user) {
			this.user = user;
		}

		public List<User> getUsers() {
			return users;
		}

		public void setUsers(List<User> users) {
			this.users = users;
		}

		public int getId() {
	        return id;
	    }

	    public void setId(int id) {
	        this.id = id;
	    }
	    public int getAid() {
	        return aid;
	    }

	    public void setAid(int aid) {
	        this.aid = aid;
	    }

	    public int getPageNow() {
	        return pageNow;
	    }

	    public void setPageNow(int pageNow) {
	        this.pageNow = pageNow;
	    }

	    public int getPageSize() {
	        return pageSize;
	    }

	    public void setPageSize(int pageSize) {
	        this.pageSize = pageSize;
	    }
	    public int getIntRowCount() {
	        return intRowCount;
	    }

	    public void setIntRowCount(int intRowCount) {
	        this.intRowCount = intRowCount;
	    }

	    public int getIntPageCount() {
	        return intPageCount;
	    }

	    public void setIntPageCount(int intPageCount) {
	        this.intPageCount = intPageCount;
	    }
	    public int getK() {
	        return k;
	    }

	    public void setK(int k) {
	        this.k = k;
	    }
	@SuppressWarnings("unchecked")
	    @Override
	//显示列表
	    public String execute() throws Exception {

	        IuserDao npage=new UserDao();
	        intRowCount=npage.count();
	        k=(intRowCount + pageSize - 1) / pageSize;
	        intPageCount = (intRowCount + pageSize - 1) / pageSize;//计算出总页数
	      
	        if(pageNow<1){
	            pageNow=1;
	        }
	        
	        if(pageNow > intPageCount)
	             pageNow=intPageCount;
	        
	        
	         i = (pageNow -1)*pageSize;
	         IuserDao nlist=new UserDao();
	        if(null!=nlist.displayUser(i,pageSize)){
	        users = nlist.displayUser(i,pageSize);
	            return SUCCESS;
	        }else{
	            return "failure";
	        }
	    }
	       
	}


 struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="users" extends="struts-default">

       <action name="list" class="page.PageAction" >
            <result>/listUsers.jsp</result>
            <result name="failure">/Showfailure.jsp</result>
        </action>

</package>
</struts>
 


 

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>bornToPage</display-name>
   <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <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>
</web-app>

 

listUser.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <base href="<%=basePath%>">
        <title>My JSP 'index.jsp' starting page</title>
    </head>
    <body>
<center><table border = "1">
<tr>
	<td>id</td>
	<td>name</td>
	<td>pass</td>
	
</tr>
<s:iterator value="users"  id = "user">
<tr>
	<td><s:property value = "#user.id"/></td>
	<td><s:property value = "#user.userName"/></td>
	<td><s:property value = "#user.password"/></td>
	
</tr>
</s:iterator>
</table>
</center>
        <center>
        共<s:property value="intRowCount"/>记录&nbsp;&nbsp;
        第<s:property value="pageNow"/>页&nbsp;&nbsp;
     <s:url id="url_pre" value="list.action">   
         <s:param name="pageNow" value="pageNow-1"></s:param>   
     </s:url>   
  
     <s:url id="url_next" value="list.action">   
         <s:param name="pageNow" value="pageNow+1"></s:param>   
     </s:url>   
<s:if test="intPageCount!=null">	
<s:bean name="org.apache.struts2.util.Counter" id="counter">
   <s:param name="first" value="1" />
   <s:param name="last" ><s:property value="intPageCount"/></s:param>
   <s:iterator>
      
      <s:url id="url" value="list.action">   
            <s:param name="pageNow" ><s:property /></s:param>   
        </s:url>  
      <s:a href="%{url}"><s:property /></s:a>
   </s:iterator>
</s:bean>
</s:if>
    
    
     <s:if test="pageNow==1">
    <s:a href="%{url_pre}">最前一页</s:a>
     </s:if>
     <s:else>
     <s:a href="%{url_pre}">上一页</s:a>
     </s:else>
     <s:if test="pageNow==k">
     <s:a href="%{url_next}">最后一页</s:a>
       </s:if>
       <s:else>
       <s:a href="%{url_next}">下一页</s:a>
       </s:else>
       </center>
    </body>
</html>

 

直接jsp运行后 不显示分页 需在地址栏里写上http://localhost:8080/bornToPage/list.action才能正常显示(提前子在数据库多插入几条数据)

你可能感兴趣的:(oracle,jsp,Hibernate,struts,javaee)