开发环境: eclipse3.5 oracle11G jkd: 1.6 tomcat6.0 struts2.1.6 spring2.5 hibernate3.2
看了 http://www.blogjava.net/rongxh7 提供的struts2+spring+hibernate做的分页方案后写的一个完整的例子.
listMember.jsp 文件
Code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>分页显示</title>
</head>
<body>
<s:iterator value="pageBean.list">
<s:property value="id"/>
<s:property value="firstname"/>
<s:property value="lastname"/>
<a href="updateUser.action?id=<s:property value="firstname"/>">modify</a>
<a href="deleteUser.action?id=<s:property value="lastname"/>" οnclick="return askDel()"/>delete</a><br/>
</s:iterator>
共<s:property value="pageBean.allRow"/> 条记录
共<s:property value="pageBean.totalPage"/> 页
当前第<s:property value="pageBean.currentPage"/>页<br/>
<s:if test="%{pageBean.currentPage == 1}">
第一页 上一页
</s:if>
<s:else>
<a href="listMyArticle.action?page=1">第一页</a>
<a href="listMyArticle.action?page=<s:property value="%{pageBean.currentPage-1}"/>">上一页</a>
</s:else>
<s:if test="%{pageBean.currentPage != pageBean.totalPage}">
<a href="listMyArticle.action?page=<s:property value="%{pageBean.currentPage+1}"/>">下一页</a>
<a href="listMyArticle.action?page=<s:property value="pageBean.totalPage"/>">最后一页</a>
</s:if>
<s:else>
下一页 最后一页
</s:else>
</table>
</body>
</html>index.jsp 文件
Code
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my javaEE page. test![](https://www.cnblogs.com/Images/dot.gif)
![](https://www.cnblogs.com/Images/dot.gif)
.wj <br>
<h1><font color="blue">Operation List</font><br/></h1>
<s:a href="save.jsp">Save User</s:a><br/>
<s:a href="listUser.action">List Users</s:a><br/>
<s:a href="listMyArticle.action">pagination</s:a>
</body>
</html>
struts.xml 文件
Code
<?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="user" extends="struts-default">
<action name="saveUser" class="saveUserAction">
<result name="success" type="redirect">listUser.action</result>
<!-- <result>/save.jsp</result> -->
<result name="input">/save.jsp</result>
</action>
<action name="listUser" class="listUserAction">
<result>/list.jsp</result>
</action>
<action name="deleteUser" class="removeUserAction">
<result name="success" type="redirect">listUser.action</result>
</action>
<action name="updateSUser" class="updateSUserAction">
<result name="success">/updateUser.jsp</result>
</action>
<action name="updateUser" class="updateUserAction">
<result name="success" type="redirect">listUser.action</result>
<result name="input">/updateUser.jsp</result>
</action>
<action name="listMyArticle" class="listPageAction">
<!--
<result name="success" type="redirect">testJsp/listMember.jsp</result>
-->
<result>testJsp/listMember.jsp</result>
</action>
</package>
</struts>action文件 ListMember.java
Code
package com.pms.action.user;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.pms.bean.PageBean;
import com.pms.service.MemberService;
public class ListMember extends ActionSupport {
private MemberService memberService;
public void setMemberService(MemberService memberService) {
this.memberService = memberService;
}
private int page; //第几页
private PageBean pageBean; //包含分页信息的bean
public int getPage() {
return page;
}
public void setPage(int page) { //若URL中无此参数,会默认为第1页
this.page = page;
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public String execute() throws Exception {
//分页的pageBean,参数pageSize表示每页显示记录数,page为当前页
this.pageBean = memberService.queryForPage(2, page);
return SUCCESS;
}
}
PageBean.java bean类
Code
package com.pms.bean;
import java.util.List;
//下面我们来新建一个保存分页信息的类PageBean
public class PageBean {
private List list; //要返回的某一页的记录列表
private int allRow; //总记录数
private int totalPage; //总页数
private int currentPage; //当前页
private int pageSize; //每页记录数
private boolean isFirstPage; //是否为第一页
private boolean isLastPage; //是否为最后一页
private boolean hasPreviousPage; //是否有前一页
private boolean hasNextPage; //是否有下一页
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public int getAllRow() {
return allRow;
}
public void setAllRow(int allRow) {
this.allRow = allRow;
}
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 getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* 以下判断页的信息,只需getter方法(is方法)即可
* @return
*/
public boolean isFirstPage() {
return currentPage == 1; // 如是当前页是第1页
}
public boolean isLastPage() {
return currentPage == totalPage; //如果当前页是最后一页
}
public boolean isHasPreviousPage() {
return currentPage != 1; //只要当前页不是第1页
}
public boolean isHasNextPage() {
return currentPage != totalPage; //只要当前页不是最后1页
}
/**
* 初始化分页信息
*/
public void init()
{
this.isFirstPage=isFirstPage();
this.isLastPage=isLastPage();
this.hasPreviousPage=isHasPreviousPage();
this.hasNextPage=isHasNextPage();
}
/**
* 计算总页数,静态方法,供外部直接通过类名调用
* @param pageSize 每页记录数
* @param allRow 总记录数
* @return 总页数
*/
public static int countTotalPage(final int pageSize,final int allRow){
int totalPage = allRow % pageSize == 0 ? allRow/pageSize : allRow/pageSize+1;
return totalPage;
}
/**
* 计算当前页开始记录
* @param pageSize 每页记录数
* @param currentPage 当前第几页
* @return 当前页开始记录号
*/
public static int countOffset(final int pageSize,final int currentPage){
final int offset = pageSize*(currentPage-1);
return offset;
}
/**
* 计算当前页,若为0或者请求的URL中没有"?page=",则用1代替
* @param page 传入的参数(可能为空,即0,则返回1)
* @return 当前页
*/
public static int countCurrentPage(int page){
final int curPage = (page==0?1:page);
return curPage;
}
}
User.java bean类 这里可存我显示的数据.
Code
package com.pms.bean;
public class User {
private Integer id;
private String firstname;
private String lastname;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
User.hbm.xml 映射数据库的文件
Code
<?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>
<class name="com.pms.bean.User" table="users">
<id name="id" type="java.lang.Integer" column="id">
<generator class="increment"></generator>
<!-- <generator class="increment"> <generator class="native"></generator改成native -->
</id>
<property name="firstname" type="string" column="firstname" length="50"></property>
<property name="lastname" type="string" column="lastname" length="50"></property>
<property name="age" type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>dao类 MemberDao.java
Code
package com.pms.dao;
import java.util.List;
//DAO层接口的设计,在MemberDao接口中定义了如下两个方法:
public interface MemberDao {
/**
* 分页查询
* @param hql 查询的条件
* @param offset 开始记录
* @param length 一次查询几条记录
* @return
*/
public List queryForPage(final String hql,final int offset,final int length);
/**
* 查询所有记录数
* @param hql 查询的条件
* @return 总记录数
*/
public int getAllRowCount(String hql);
}
dao的实现类 MemberDaoImpl.java
Code
package com.pms.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.hibernate.Query;
import com.pms.bean.User;
import com.pms.dao.MemberDao;
//DAO层实现类MemberDaoImpl对上面两个方法的实现如下:
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao {
/**
* 分页查询
*
* 这个类继承了HibernateDaoSupport类,HibernateDaoSupport是Spring提供的对Hibernate支持的类,
* getHibernateTemplate().executeFind(new HibernateCallback(){
.})方法中的参数,
* 我们使用了接口回调,在其参数内,我们能像原生的Hibernate一样调用query.setFirstResult(offset)
* 和query.setMaxResults(length)来实现分页查询功能。
* @param hql
* 查询的条件
* @param offset
* 开始记录
* @param length
* 一次查询几条记录
* @return
*/
public List queryForPage(final String hql, final int offset,final int length) {
List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)throws HibernateException, SQLException {
System.out.println("查询SQL语句hql: " + hql);
Query query = session.createQuery(hql);
//org.hibernate.Query query = session.createQuery(hql);
System.out.println("中华人民共和国");
System.out.println("offsetoffsetoffsetoffsetoffsetoffsetoffset "+ offset);
System.out.println("lengthlengthlengthlengthlengthlengthlength " +length);
// query.setFirstResult(0);
//if (offset >= 0 && length > 0) {
query.setFirstResult(offset);
query.setMaxResults(length);
//}
System.out.println("ddddddddddddddddddddddddddddddddddddddddddddddddd");
List list = query.list();
for(int i=0; i<list.size(); i++){
User ur=(User)list.get(i);
System.out.println("getId " + ur.getId());
System.out.println("getFirstname " + ur.getFirstname());
System.out.println("getLastname " + ur.getLastname());
}
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
return list;
}
});
return list;
}
/*
public List queryForPage(final String hql,final int offset,final int length){
List list = getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
Query query = session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
});
return list;
}*/
/**
* 查询所有记录数
*
* @return 总记录数
*/
public int getAllRowCount(String hql) {
return getHibernateTemplate().find(hql).size();
}
}
service类 MemberService.java
Code
package com.pms.service;
import com.pms.bean.PageBean;
public interface MemberService {
/**
* 分页查询
* @param currentPage 当前第几页
* @param pageSize 每页大小
* @return 封闭了分页信息(包括记录集list)的Bean
*/
public PageBean queryForPage(int pageSize,int currentPage);
}
service的实现类 MemberServiceImpl.java
Code
package com.pms.service.impl;
import java.util.List;
import com.pms.bean.PageBean;
import com.pms.bean.User;
import com.pms.dao.MemberDao;
import com.pms.service.MemberService;
public class MemberServiceImpl implements MemberService {
//通过applicationContext.xml配置文件注入MemberDao的值
private MemberDao memberDao;
public void setMemberDao(MemberDao memberDao) {
this.memberDao = memberDao;
}
/** *//**
* 分页查询
* @param currentPage 当前第几页
* @param pageSize 每页大小
* @return 封闭了分页信息(包括记录集list)的Bean
*/
@SuppressWarnings("unchecked")
public PageBean queryForPage(int pageSize,int page){
final String hql="from User user order by user.id asc";
// final String hql="from User user";
// final String hql = "from Member"; //查询语句
int allRow = memberDao.getAllRowCount(hql); //总记录数
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
System.out.println("总记录数 allRow "+allRow);
System.out.println("cccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
int totalPage = PageBean.countTotalPage(pageSize, allRow); //总页数
// final int offset = PageBean.countOffset(pageSize, page); //当前页开始记录
int pageStartR=PageBean.countOffset(pageSize, page); //当前页开始记录
if(pageStartR<0)
{
pageStartR=0;
}
final int offset = pageStartR; //当前页开始记录
System.out.println("总页数 totalPage " + totalPage);
System.out.println("当前页开始记录 offset " + offset);
final int length = pageSize; //每页记录数
final int currentPage = PageBean.countCurrentPage(page);
System.out.println("每页记录数 length" + length);
System.out.println("当前页currentPage " + currentPage);
List<User> list = (List<User>)memberDao.queryForPage(hql,offset, length); //"一页"的记录
// List<MemberDao> list = memberDao.queryForPage(hql,offset, length); //"一页"的记录
System.out.println("查询SQL语句hql 55555555: " + hql);
//把分页信息保存到Bean中
PageBean pageBean = new PageBean();
pageBean.setPageSize(pageSize);
pageBean.setCurrentPage(currentPage);
pageBean.setAllRow(allRow);
pageBean.setTotalPage(totalPage);
pageBean.setList(list);
pageBean.init();
return pageBean;
}
}
spring的applicationContext.xml的配置文件
Code
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- 连mysql -->
<!--
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://9.16.66.28:3306/wjdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
-->
<!-- 连MS-SQL
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"></property>
<property name="url" value="jdbc:jtds:sqlserver://11.11.11.88:1433;DatabaseName=testDB"></property>
<property name="username" value="sa"></property>
<property name="password" value="Wang.Jun2009"></property>
-->
<!-- 连 Oracle -->
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@11.11.1.106:1521:orcl"></property>
<property name="username" value="wangjun"></property>
<property name="password" value="123456"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="500"></property>
<property name="defaultAutoCommit" value="true"></property>
</bean>
<!--Hibernate Session工厂配置-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- sessionFactory相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!--采用Hibernate2.0的HSql解释器,解决了中文问题-->
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<!--打开Query Cache开关,需要Cache的query需要单独配置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
<!--
<property name="lobHandler" ref="lobHandler"/>
-->
<property name="mappingResources">
<list>
<!-- hibernate实体映射文件!即生成的 *.hbm.xml-->
<value>com/pms/bean/User.hbm.xml</value>
</list>
</property>
</bean>
<!--事务管理器配置-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="userDao" class="com.pms.dao.impl.UserDAOImpl" scope="singleton">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="userService" class="com.pms.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="saveUserAction" class="com.pms.action.user.SaveUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="listUserAction" class="com.pms.action.user.ListUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="removeUserAction" class="com.pms.action.user.RemoveUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="updateSUserAction" class="com.pms.action.user.UpdateSUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="updateUserAction" class="com.pms.action.user.UpdateUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="memberDao" class="com.pms.dao.impl.MemberDaoImpl" scope="singleton">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="MemberService" class="com.pms.service.impl.MemberServiceImpl">
<property name="memberDao" ref="memberDao"></property>
</bean>
<bean id="listPageAction" class="com.pms.action.user.ListMember" scope="prototype">
<property name="memberService" ref="MemberService"></property>
</bean>
</beans>
sql脚本
1 aa dd modify delete
2 23 12 modify delete
共13 条记录 共7 页 当前第1页
第一页 上一页 下一页 最后一页
========代码结束, 下面再来一点我做时的出的问题.==================
最后在这里我顺便说一下做时出现的一个问题:
在DaoImpl类中 分页方法中:
看了 http://www.blogjava.net/rongxh7 提供的struts2+spring+hibernate做的分页方案后写的一个完整的例子.
listMember.jsp 文件
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>分页显示</title>
</head>
<body>
<s:iterator value="pageBean.list">
<s:property value="id"/>
<s:property value="firstname"/>
<s:property value="lastname"/>
<a href="updateUser.action?id=<s:property value="firstname"/>">modify</a>
<a href="deleteUser.action?id=<s:property value="lastname"/>" οnclick="return askDel()"/>delete</a><br/>
</s:iterator>
共<s:property value="pageBean.allRow"/> 条记录
共<s:property value="pageBean.totalPage"/> 页
当前第<s:property value="pageBean.currentPage"/>页<br/>
<s:if test="%{pageBean.currentPage == 1}">
第一页 上一页
</s:if>
<s:else>
<a href="listMyArticle.action?page=1">第一页</a>
<a href="listMyArticle.action?page=<s:property value="%{pageBean.currentPage-1}"/>">上一页</a>
</s:else>
<s:if test="%{pageBean.currentPage != pageBean.totalPage}">
<a href="listMyArticle.action?page=<s:property value="%{pageBean.currentPage+1}"/>">下一页</a>
<a href="listMyArticle.action?page=<s:property value="pageBean.totalPage"/>">最后一页</a>
</s:if>
<s:else>
下一页 最后一页
</s:else>
</table>
</body>
</html>
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my javaEE page. test
![](https://www.cnblogs.com/Images/dot.gif)
![](https://www.cnblogs.com/Images/dot.gif)
![](https://www.cnblogs.com/Images/dot.gif)
<h1><font color="blue">Operation List</font><br/></h1>
<s:a href="save.jsp">Save User</s:a><br/>
<s:a href="listUser.action">List Users</s:a><br/>
<s:a href="listMyArticle.action">pagination</s:a>
</body>
</html>
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?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="user" extends="struts-default">
<action name="saveUser" class="saveUserAction">
<result name="success" type="redirect">listUser.action</result>
<!-- <result>/save.jsp</result> -->
<result name="input">/save.jsp</result>
</action>
<action name="listUser" class="listUserAction">
<result>/list.jsp</result>
</action>
<action name="deleteUser" class="removeUserAction">
<result name="success" type="redirect">listUser.action</result>
</action>
<action name="updateSUser" class="updateSUserAction">
<result name="success">/updateUser.jsp</result>
</action>
<action name="updateUser" class="updateUserAction">
<result name="success" type="redirect">listUser.action</result>
<result name="input">/updateUser.jsp</result>
</action>
<action name="listMyArticle" class="listPageAction">
<!--
<result name="success" type="redirect">testJsp/listMember.jsp</result>
-->
<result>testJsp/listMember.jsp</result>
</action>
</package>
</struts>
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.action.user;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.pms.bean.PageBean;
import com.pms.service.MemberService;
public class ListMember extends ActionSupport {
private MemberService memberService;
public void setMemberService(MemberService memberService) {
this.memberService = memberService;
}
private int page; //第几页
private PageBean pageBean; //包含分页信息的bean
public int getPage() {
return page;
}
public void setPage(int page) { //若URL中无此参数,会默认为第1页
this.page = page;
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public String execute() throws Exception {
//分页的pageBean,参数pageSize表示每页显示记录数,page为当前页
this.pageBean = memberService.queryForPage(2, page);
return SUCCESS;
}
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.bean;
import java.util.List;
//下面我们来新建一个保存分页信息的类PageBean
public class PageBean {
private List list; //要返回的某一页的记录列表
private int allRow; //总记录数
private int totalPage; //总页数
private int currentPage; //当前页
private int pageSize; //每页记录数
private boolean isFirstPage; //是否为第一页
private boolean isLastPage; //是否为最后一页
private boolean hasPreviousPage; //是否有前一页
private boolean hasNextPage; //是否有下一页
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public int getAllRow() {
return allRow;
}
public void setAllRow(int allRow) {
this.allRow = allRow;
}
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 getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* 以下判断页的信息,只需getter方法(is方法)即可
* @return
*/
public boolean isFirstPage() {
return currentPage == 1; // 如是当前页是第1页
}
public boolean isLastPage() {
return currentPage == totalPage; //如果当前页是最后一页
}
public boolean isHasPreviousPage() {
return currentPage != 1; //只要当前页不是第1页
}
public boolean isHasNextPage() {
return currentPage != totalPage; //只要当前页不是最后1页
}
/**
* 初始化分页信息
*/
public void init()
{
this.isFirstPage=isFirstPage();
this.isLastPage=isLastPage();
this.hasPreviousPage=isHasPreviousPage();
this.hasNextPage=isHasNextPage();
}
/**
* 计算总页数,静态方法,供外部直接通过类名调用
* @param pageSize 每页记录数
* @param allRow 总记录数
* @return 总页数
*/
public static int countTotalPage(final int pageSize,final int allRow){
int totalPage = allRow % pageSize == 0 ? allRow/pageSize : allRow/pageSize+1;
return totalPage;
}
/**
* 计算当前页开始记录
* @param pageSize 每页记录数
* @param currentPage 当前第几页
* @return 当前页开始记录号
*/
public static int countOffset(final int pageSize,final int currentPage){
final int offset = pageSize*(currentPage-1);
return offset;
}
/**
* 计算当前页,若为0或者请求的URL中没有"?page=",则用1代替
* @param page 传入的参数(可能为空,即0,则返回1)
* @return 当前页
*/
public static int countCurrentPage(int page){
final int curPage = (page==0?1:page);
return curPage;
}
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.bean;
public class User {
private Integer id;
private String firstname;
private String lastname;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?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>
<class name="com.pms.bean.User" table="users">
<id name="id" type="java.lang.Integer" column="id">
<generator class="increment"></generator>
<!-- <generator class="increment"> <generator class="native"></generator改成native -->
</id>
<property name="firstname" type="string" column="firstname" length="50"></property>
<property name="lastname" type="string" column="lastname" length="50"></property>
<property name="age" type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.dao;
import java.util.List;
//DAO层接口的设计,在MemberDao接口中定义了如下两个方法:
public interface MemberDao {
/**
* 分页查询
* @param hql 查询的条件
* @param offset 开始记录
* @param length 一次查询几条记录
* @return
*/
public List queryForPage(final String hql,final int offset,final int length);
/**
* 查询所有记录数
* @param hql 查询的条件
* @return 总记录数
*/
public int getAllRowCount(String hql);
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.hibernate.Query;
import com.pms.bean.User;
import com.pms.dao.MemberDao;
//DAO层实现类MemberDaoImpl对上面两个方法的实现如下:
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao {
/**
* 分页查询
*
* 这个类继承了HibernateDaoSupport类,HibernateDaoSupport是Spring提供的对Hibernate支持的类,
* getHibernateTemplate().executeFind(new HibernateCallback(){
![](https://www.cnblogs.com/Images/dot.gif)
* 我们使用了接口回调,在其参数内,我们能像原生的Hibernate一样调用query.setFirstResult(offset)
* 和query.setMaxResults(length)来实现分页查询功能。
* @param hql
* 查询的条件
* @param offset
* 开始记录
* @param length
* 一次查询几条记录
* @return
*/
public List queryForPage(final String hql, final int offset,final int length) {
List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)throws HibernateException, SQLException {
System.out.println("查询SQL语句hql: " + hql);
Query query = session.createQuery(hql);
//org.hibernate.Query query = session.createQuery(hql);
System.out.println("中华人民共和国");
System.out.println("offsetoffsetoffsetoffsetoffsetoffsetoffset "+ offset);
System.out.println("lengthlengthlengthlengthlengthlengthlength " +length);
// query.setFirstResult(0);
//if (offset >= 0 && length > 0) {
query.setFirstResult(offset);
query.setMaxResults(length);
//}
System.out.println("ddddddddddddddddddddddddddddddddddddddddddddddddd");
List list = query.list();
for(int i=0; i<list.size(); i++){
User ur=(User)list.get(i);
System.out.println("getId " + ur.getId());
System.out.println("getFirstname " + ur.getFirstname());
System.out.println("getLastname " + ur.getLastname());
}
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
return list;
}
});
return list;
}
/*
public List queryForPage(final String hql,final int offset,final int length){
List list = getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
Query query = session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
});
return list;
}*/
/**
* 查询所有记录数
*
* @return 总记录数
*/
public int getAllRowCount(String hql) {
return getHibernateTemplate().find(hql).size();
}
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.service;
import com.pms.bean.PageBean;
public interface MemberService {
/**
* 分页查询
* @param currentPage 当前第几页
* @param pageSize 每页大小
* @return 封闭了分页信息(包括记录集list)的Bean
*/
public PageBean queryForPage(int pageSize,int currentPage);
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
package com.pms.service.impl;
import java.util.List;
import com.pms.bean.PageBean;
import com.pms.bean.User;
import com.pms.dao.MemberDao;
import com.pms.service.MemberService;
public class MemberServiceImpl implements MemberService {
//通过applicationContext.xml配置文件注入MemberDao的值
private MemberDao memberDao;
public void setMemberDao(MemberDao memberDao) {
this.memberDao = memberDao;
}
/** *//**
* 分页查询
* @param currentPage 当前第几页
* @param pageSize 每页大小
* @return 封闭了分页信息(包括记录集list)的Bean
*/
@SuppressWarnings("unchecked")
public PageBean queryForPage(int pageSize,int page){
final String hql="from User user order by user.id asc";
// final String hql="from User user";
// final String hql = "from Member"; //查询语句
int allRow = memberDao.getAllRowCount(hql); //总记录数
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
System.out.println("总记录数 allRow "+allRow);
System.out.println("cccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
int totalPage = PageBean.countTotalPage(pageSize, allRow); //总页数
// final int offset = PageBean.countOffset(pageSize, page); //当前页开始记录
int pageStartR=PageBean.countOffset(pageSize, page); //当前页开始记录
if(pageStartR<0)
{
pageStartR=0;
}
final int offset = pageStartR; //当前页开始记录
System.out.println("总页数 totalPage " + totalPage);
System.out.println("当前页开始记录 offset " + offset);
final int length = pageSize; //每页记录数
final int currentPage = PageBean.countCurrentPage(page);
System.out.println("每页记录数 length" + length);
System.out.println("当前页currentPage " + currentPage);
List<User> list = (List<User>)memberDao.queryForPage(hql,offset, length); //"一页"的记录
// List<MemberDao> list = memberDao.queryForPage(hql,offset, length); //"一页"的记录
System.out.println("查询SQL语句hql 55555555: " + hql);
//把分页信息保存到Bean中
PageBean pageBean = new PageBean();
pageBean.setPageSize(pageSize);
pageBean.setCurrentPage(currentPage);
pageBean.setAllRow(allRow);
pageBean.setTotalPage(totalPage);
pageBean.setList(list);
pageBean.init();
return pageBean;
}
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- 连mysql -->
<!--
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://9.16.66.28:3306/wjdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
-->
<!-- 连MS-SQL
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"></property>
<property name="url" value="jdbc:jtds:sqlserver://11.11.11.88:1433;DatabaseName=testDB"></property>
<property name="username" value="sa"></property>
<property name="password" value="Wang.Jun2009"></property>
-->
<!-- 连 Oracle -->
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@11.11.1.106:1521:orcl"></property>
<property name="username" value="wangjun"></property>
<property name="password" value="123456"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="500"></property>
<property name="defaultAutoCommit" value="true"></property>
</bean>
<!--Hibernate Session工厂配置-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- sessionFactory相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!--采用Hibernate2.0的HSql解释器,解决了中文问题-->
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<!--打开Query Cache开关,需要Cache的query需要单独配置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
<!--
<property name="lobHandler" ref="lobHandler"/>
-->
<property name="mappingResources">
<list>
<!-- hibernate实体映射文件!即生成的 *.hbm.xml-->
<value>com/pms/bean/User.hbm.xml</value>
</list>
</property>
</bean>
<!--事务管理器配置-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="userDao" class="com.pms.dao.impl.UserDAOImpl" scope="singleton">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="userService" class="com.pms.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="saveUserAction" class="com.pms.action.user.SaveUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="listUserAction" class="com.pms.action.user.ListUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="removeUserAction" class="com.pms.action.user.RemoveUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="updateSUserAction" class="com.pms.action.user.UpdateSUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="updateUserAction" class="com.pms.action.user.UpdateUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>
<bean id="memberDao" class="com.pms.dao.impl.MemberDaoImpl" scope="singleton">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="MemberService" class="com.pms.service.impl.MemberServiceImpl">
<property name="memberDao" ref="memberDao"></property>
</bean>
<bean id="listPageAction" class="com.pms.action.user.ListMember" scope="prototype">
<property name="memberService" ref="MemberService"></property>
</bean>
</beans>
代码中这里的ID是自动增长的。
create table users
(
id INTEGER ,
firstname varchar2 ( 50 ),
lastname varchar2 ( 50 ),
age INTEGER
)
到这里就已可以完整的看到结果了:
create table users
(
id INTEGER ,
firstname varchar2 ( 50 ),
lastname varchar2 ( 50 ),
age INTEGER
)
1 aa dd modify delete
2 23 12 modify delete
共13 条记录 共7 页 当前第1页
第一页 上一页 下一页 最后一页
========代码结束, 下面再来一点我做时的出的问题.==================
最后在这里我顺便说一下做时出现的一个问题:
在DaoImpl类中 分页方法中:
query.setFirstResult(offset);
query.setMaxResults(length);
以上分页的这两句代码我加了就会报错,不加则 可全部显示出来。
query.setMaxResults(length);
以上分页的这两句代码我加了就会报错,不加则 可全部显示出来。
根据提示是不能执行查询语句,可我觉得不加分页能全部显示,查询语句就应该没错。
报错提示:
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:615) org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424) org.springframework.orm.hibernate3.HibernateTemplate.executeFind(HibernateTemplate.java:343) com.pms.dao.impl.MemberDaoImpl.queryForPage(MemberDaoImpl.java:61)
===============源码=============================================
public List queryForPage(final String hql,final int offset,final int length){
List list = getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
Query query = session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
});
return list;
}
========解决方法:=================
List list = getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
Query query = session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
});
return list;
}
问题原因:
在Spring 的applicationContext.xml文件中少了。
在Hibernate session工厂中少了:
<!--采用Hibernate2.0的HSql解释器,解决了中文问题-->
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<!--打开Query Cache开关,需要Cache的query需要单独配置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>