SSH:Struts2.2+Hibernate3.6+Spring3.1分页示例[转]
参考资料
1 ssh分页(多个例子)
http://useryouyou.iteye.com/blog/593954
2 ssh2分页例子
http://459104018-qq-com.iteye.com/blog/467196
3 ssh2分页
http://blog.csdn.net/shmily2038/archive/2009/12/28/5090044.aspx
注意事项:
此示例是在:Struts2.2+Spring3.1+Hibernate3.6整合(登录示例及CRUD操作)基础上加的分页功能:
http://liuzidong.iteye.com/blog/935493
实现功能:分页,排序,设置每页显示多少条,转到第多少页
调用说明:
1 导入只需要:com.liuzd.page包下的类或者将page.jar加入WEB-INF/lib下也行^_^
2 Struts2前台类实现: BaseAction父类
3 在子类方法中调用父类提供的方法:
Page page = executePage(querySql,totalCount," id desc ");
需要传递三个参数就行了: querySql(查询sql语句), totalCount(总行数),
" id desc "(排序的列名与排序方式)
4 返回分页数据
List<User> users = this.userService.getUserListByPage(page);
5 在spring配置文件中请保持有: jdbcTemplate与hibernateTemplate这二个Bean的名字,否则dbUtil类不能使用
6 具体可参见:四的说明
一 运行环境:XP+Myeclipse6.6+WebLogic92+Oracle10g
二 工程相关图片:
1 DEMO图片
2 工程代码图片
3 page.jar图片
三 此示例是在:
Struts2.2+Spring3.1+Hibernate3.6整合(登录示例及CRUD操作)基础上加的分页功能:
http://liuzidong.iteye.com/blog/935493,jar包在此页面中下载
四 关注类及页面:
1 BaseAction类(可能你在项目有其它的父类要使用,只要关注这个类中的: protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc)方法就行了,方法中的参数不用修改,它来自于page.jsp,你可拷贝这个方法到你的父类中就实现了分页功能,分页类详见注释)
2 UserAction子类(只关注:方法:userList()中的调用方式)
3 UserDAOImpl类(关注方法:public List<User> getUserListByPage(final Page page) )
4 userList.jsp页面
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
在排序处:
- <font color='red'>${page.sortName eq "username" ? page.sortInfo :page.defaultInfo}</font>
在下面加上:
- <jsp:include page="/page/page.jsp">
- <jsp:param name="url" value="userAction!userList.action" />
- <!-- 演示传值:要用%26 -->
- <jsp:param name="urlParams" value="%26age=2" />
- </jsp:include>
四 要关注的类与页面
1 BaseAction.java
- package com.liuzd.common;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.ServletActionContext;
- import org.apache.struts2.interceptor.SessionAware;
- import com.liuzd.page.Page;
- import com.liuzd.page.PageUtil;
- import com.liuzd.page.PageState;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * 基本Struts2的分页父类
- * @author liuzd
- * @version 1.0 2011-05-12
- * @since JDK1.5
- * */
- public class BaseAction extends ActionSupport implements SessionAware{
- private static final long serialVersionUID = 1L;
- public void setSession(Map<String, Object> sessionMap) {
- }
- protected Map<String,Object> getMapSession(){
- return (Map<String,Object>)ActionContext.getContext().getSession();
- }
- protected Object getMapSessionGet(String key){
- return getMapSession().get(key);
- }
- protected void setMapSessionPut(String key,Object value){
- getMapSession().put(key, value);
- }
- /***
- * 获取请求对象
- * */
- protected HttpServletRequest getRequest(){
- return ServletActionContext.getRequest ();
- }
- /***
- * 获取会话对象
- * */
- protected javax.servlet.http.HttpSession getSession(){
- return getRequest().getSession();
- }
- /***
- * 设置请求参数
- * */
- protected void setRequestAttribute(String attribute,Object attrValue){
- getRequest().setAttribute(attribute, attrValue);
- }
- /***
- * 获取请求参数
- * */
- protected Object getRequestAttribute(String attribute){
- return getRequest().getAttribute(attribute);
- }
- /***
- * 设置Session参数与值
- * */
- protected void setSessionAttribute(String attribute,Object attrValue){
- getSession().setAttribute(attribute, attrValue);
- }
- /***
- * 获取Session参数与值
- * */
- protected Object getSessionAttribute(String attribute){
- return getSession().getAttribute(attribute);
- }
- /**
- * oracel的三层分页语句
- * 子类在展现数据前,进行分页计算!
- * @param querySql 查询的SQL语句,未进行分页
- * @param totalCount 根据查询SQL获取的总条数
- * @param columnNameDescOrAsc 列名+排序方式 : ID DESC or ASC
- */
- protected Page executePage(String querySql,Long totalCount,String columnNameDescOrAsc){
- String oracleSql = PageUtil.createQuerySql(querySql,columnNameDescOrAsc);
- if(null == totalCount){
- totalCount = 0L;
- }
- /**页面状态,这个状态是分页自带的,与业务无关*/
- String pageAction = getRequest().getParameter("pageAction");
- String value = null;
- /**获取下标判断分页状态*/
- int index = PageState.getOrdinal(pageAction);
- if(0 == index){
- /**每页显示多少条*/
- value = getRequest().getParameter("everyPage");
- }
- Page page = null;
- /**
- * index < 1 只有二种状态
- * 1 当首次调用时,分页状态类中没有值为 NULL 返回 -1
- * 2 当页面设置每页显示多少条: index=0,当每页显示多少条时,分页类要重新计算
- * */
- if(index < 1){
- page = PageUtil.inintPage(oracleSql,totalCount,index,value,getPage());
- }else{
- /**
- * 当页面排序时
- * */
- if(5 == index){
- value = getRequest().getParameter("sortName");
- /**
- * 到指定多少页
- * */
- }else if(6 == index){
- value = getRequest().getParameter("currentPage");
- }
- page = PageUtil.execPage(index,value,getPage());
- }
- setSession(page);
- return page;
- }
- private Page getPage() {
- Page page = (Page)getSession().getAttribute(PageUtil.SESSION_PAGE_KEY);
- if(page == null){
- page = new Page();
- }
- return page;
- }
- private void setSession(Page page) {
- getSession().setAttribute(PageUtil.SESSION_PAGE_KEY,page);
- }
- }
2 UserAction.java
- package com.liuzd.s2sh.web;
- import java.util.List;
- import javax.annotation.Resource;
- import org.springframework.context.annotation.Scope;
- import org.springframework.stereotype.Component;
- import com.liuzd.common.BaseAction;
- import com.liuzd.common.DbUtils;
- import com.liuzd.page.Page;
- import com.liuzd.s2sh.entity.User;
- import com.liuzd.s2sh.service.UserService;
- @Component("u")
- @Scope("prototype")
- public class UserAction extends BaseAction {
- private static final long serialVersionUID = 1L;
- private String message = null;
- private User user = null;
- private String action = null;
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- @Override
- public String execute() throws Exception {
- System.out.println("user: " + user);
- User dbUser = this.userService.checkUserExits(user);
- if (null != dbUser) {
- message = "用户: " + user.getUsername() + "登录成功";
- System.out.println(message);
- getMapSession().put("sessionUser", dbUser);
- return userList();
- //return "success";
- }
- message = "用户: " + user.getUsername() + "登录失败";
- return "fail";
- }
- public String loadUser() {
- action = "update";
- message = "编辑用户信息";
- User loadUser = new User();
- loadUser.setId(user.getId());
- user = this.userService.getUserByUid(loadUser);
- this.getRequest().setAttribute("myname", "天涯海角");
- this.getMapSession().put("mysex", "男");
- System.out.println("loaduser: " + user);
- return "user";
- }
- public String addUser() {
- action = "add";
- return "user";
- }
- public String saveUser() {
- this.userService.addUser(user);
- return "user";
- }
- public String delUser() {
- action = "del";
- this.userService.delUser(user);
- return userList();
- }
- public String editUser() {
- System.out.println("action: " + action + ",编辑用户: " + user);
- if ("update".equals(action)) {
- this.userService.editUser(user);
- } else if ("add".equals(action)) {
- saveUser();
- }
- return userList();
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- private UserService userService = null;
- private DbUtils dbUtil = null;
- public String userList() {
- //因为Hibernate分页的性能问题,使用原生sql来解决
- String querySql = "select * from users where 1=1 ";
- //用jdbc查询总条数
- Long totalCount = getDbUtil().getCountByQuerySql(querySql);
- //调用父类方法进行分页参数相关计算
- Page page = executePage(querySql,totalCount," id desc ");
- //返回分页数据
- List<User> users = this.userService.getUserListByPage(page);
- getRequest().setAttribute("userList",users);
- return "userList";
- }
- public UserService getUserService() {
- return userService;
- }
- @Resource
- public void setUserService(UserService userService) {
- this.userService = userService;
- }
- public DbUtils getDbUtil() {
- return dbUtil;
- }
- @Resource
- public void setDbUtil(DbUtils dbUtil) {
- this.dbUtil = dbUtil;
- }
- }
3 UserDAOImpl.java
- package com.liuzd.s2sh.dao.impl;
- import java.sql.SQLException;
- import java.util.List;
- import javax.annotation.Resource;
- import org.hibernate.HibernateException;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.springframework.orm.hibernate3.HibernateCallback;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.stereotype.Component;
- import com.liuzd.page.Page;
- import com.liuzd.s2sh.dao.UserDAO;
- import com.liuzd.s2sh.entity.User;
- @Component("userDao")
- public class UserDAOImpl implements UserDAO {
- private HibernateTemplate hibernateTemplate;
- public HibernateTemplate getHibernateTemplate() {
- return hibernateTemplate;
- }
- @Resource
- public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
- this.hibernateTemplate = hibernateTemplate;
- }
- @SuppressWarnings("unchecked")
- public User getUserByUserIdAndUserNameExits(User user) {
- List<User> users = hibernateTemplate
- .find("from User u where u.username = '" + user.getUsername()
- + "' and u.password='" + user.getPassword() + "'");
- if (users != null && users.size() > 0) {
- return users.get(0);
- }
- return null;
- }
- public void saveUser(User user) {
- this.hibernateTemplate.save(user);
- }
- public void delUser(User user) {
- User delUser = getUser(user);
- this.hibernateTemplate.delete(delUser);
- }
- @SuppressWarnings("unchecked")
- public List<User> finUserAll() {
- return this.hibernateTemplate.find("from User");
- }
- public User getUser(User user) {
- return this.hibernateTemplate.get(User.class, user.getId());
- }
- public void updateUser(User user) {
- this.hibernateTemplate.update(user);
- }
- @SuppressWarnings("unchecked")
- public Long getUserCount() {
- List list = this.getHibernateTemplate().find("select count(*) from User");
- return ((Long) list.iterator().next());
- }
- public Long getUserCount(String querySql) {
- return (Long) getHibernateTemplate().find(querySql).iterator().next();
- }
- @SuppressWarnings("unchecked")
- public List<User> getUserListByPage(final Page page) {
- return this.getHibernateTemplate().executeFind(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException, SQLException {
- /*Query query = session.createQuery("from User");
- //性能问题所在
- query.setFirstResult(page.getBeginIndex());
- query.setMaxResults(page.getEveryPage());
- return query.list();*/
- /* .add(Restrictions.gt("id", 2)) //greater than = id > 2
- .add(Restrictions.lt("id", 8)) //little than = id < 8
- .add(Restrictions.like("title", "t_"))
- .createCriteria("category")
- .add(Restrictions.between("id", 3, 5)) //category.id >= 3 and category.id <=5
- .add(Expression.ge("age", new Integer(20));
- .addOrder( Order.asc("name") )
- .addOrder( Order.desc("age") )
- .setMaxResults(50)
- .list();
- .add( Property.forName("name").like("F%") )
- .addOrder( Property.forName("name").asc() )
- .addOrder( Property.forName("age").desc() )
- .setMaxResults(50)
- .list();
- * */
- /*Criteria c = session.createCriteria(User.class);
- String sortName = page.getSortName();
- if(StringUtils.isNotEmpty(sortName)){
- if("asc".equals(page.getSortState())){
- c.addOrder(org.hibernate.criterion.Order.asc(sortName));
- }else{
- c.addOrder(org.hibernate.criterion.Order.desc(sortName));
- }
- }
- c.setFirstResult(page.getBeginIndex());
- c.setMaxResults(page.getEveryPage());
- return c.list();*/
- Query query = session.createSQLQuery(page.getQuerySql()).addEntity(User.class);
- return query.list();
- }
- });
- }
- }
5 JSP引用
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
- <html>
- <head>
- <title>用户集合</title>
- </head>
- <body>
- <table width="60%" border="1" cellpadding="0" align="center">
- <thead>
- <tr>
- <th style="cursor: hand;" title="按姓名进行排序" onclick="sortPage('username')" valign="top">
- 姓名<font color='red'>${page.sortName eq "username" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按年龄进行排序" onclick="sortPage('age')" valign="top">
- 年龄<font color='red'>${page.sortName eq "age" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按性别进行排序" onclick="sortPage('sex')" valign="top">
- 性别<font color='red'>${page.sortName eq "sex" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" title="按地址进行排序" onclick="sortPage('address')" valign="top">
- 地址<font color='red'>${page.sortName eq "address" ? page.sortInfo : page.defaultInfo}</font>
- </th>
- <th style="cursor: hand;" >
- 操作
- </th>
- </tr>
- </thead>
- <tbody>
- <!--
- <s:iterator value="#request.userList" status="status" >
- <tr align="center">
- <td><s:property value="username"/></td>
- <td><s:property value="age"/></td>
- <td><s:property value="sex"/></td>
- <td><s:property value="address"/></td>
- <td>
- <s:a href="userAction!addUser.action">添加</s:a> | <s:a href="userAction!loadUser.action?user.id=%{id}">编辑</s:a> |
- <a href="<s:url action="userAction!delUser.action"><s:param name="user.id" value="id"/></s:url>">删除</a>
- </td>
- </tr>
- </s:iterator>
- -->
- <c:forEach items="${requestScope.userList}" var="user">
- <tr align="center">
- <td>
- ${user.username}
- </td>
- <td>
- ${user.age}
- </td>
- <td>
- ${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"}
- </td>
- <td>
- ${user.address}
- </td>
- <td>
- <a
- href="${pageContext.request.contextPath}/userAction!addUser.action">添加</a>
- |
- <a
- href="${pageContext.request.contextPath}/userAction!loadUser.action?user.id=${user.id}">编辑</a>
- |
- <a
- href="${pageContext.request.contextPath}/userAction!delUser.action?user.id=${user.id}">删除</a>
- </td>
- </tr>
- </c:forEach>
- <jsp:include page="page.jsp">
- <jsp:param name="url" value="userAction!userList.action" />
- <!-- 演示传值:要用%26 -->
- <jsp:param name="urlParams" value="%26age=2" />
- </jsp:include>
- </tbody>
- </table>
- <br>
- <a href="${pageContext.request.contextPath}/Login.jsp">返回</a>
- <br>
- <s:debug></s:debug>
- </body>
- </html>
五 你不需要关注的分页类与JSP页面,可在附件下载jar与源码
1 Page.java
- package com.liuzd.page;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.commons.lang3.builder.ToStringBuilder;
- /**
- * 分页类
- * @author liuzd
- * @version 1.0 2011-05-12
- * @since JDK1.5
- * */
- public class Page implements java.io.Serializable{
- private static final long serialVersionUID = 1L;
- //前一页
- private Boolean hasPrePage;
- //后一页
- private Boolean hasNextPage;
- //每页显示多少条:默认10条
- private Long everyPage = 10L;
- //总页数
- private Long totalPage;
- //当前第多少页:默认第1页
- private Long currentPage = 1L;
- //开始下标
- private Long beginIndex;
- //结束下标
- private Long endinIndex;
- //总共多少条
- private Long totalCount;
- //查询结果集语句
- private String querySql;
- //未进行分页的语句
- private String initQuerySql;
- //排序列名
- private String sortName;
- //排序状态
- private String sortState;
- //排序信息
- private String sortInfo;
- //是否排序
- private Boolean sort;
- private String defaultInfo = " ";
- public String getDefaultInfo() {
- return defaultInfo;
- }
- public void setDefaultInfo(String defaultInfo) {
- this.defaultInfo = defaultInfo;
- }
- public String getSortInfo() {
- return sortInfo;
- }
- public void setSortInfo(String sortInfo) {
- this.sortInfo = sortInfo;
- }
- public String getSortName() {
- return sortName;
- }
- public void setSortName(String sortName) {
- setPageSortState(sortName);
- }
- public String getSortState() {
- return sortState;
- }
- public void setSortState(String sortState) {
- this.sortState = sortState;
- }
- public String getQuerySql() {
- return querySql;
- }
- public void setQuerySql(String querySql) {
- this.querySql = querySql;
- }
- public Page() {
- }
- /**
- * 常用,用于计算分页
- * */
- public Page(Long totalRecords){
- this.totalCount = totalRecords;
- setTotalPage(getTotalPage(totalRecords));
- }
- /**
- * 设置每页显示多少条时使用
- * */
- public Page(Long everyPage,Long totalRecords){
- this.everyPage = everyPage;
- this.totalCount = totalRecords;
- setTotalPage(getTotalPage(totalRecords));
- }
- /**
- * @param state 状态码
- * @param value 到第多少页或者设置每页显示多少条或者为排序列名
- */
- public void pageState(int index,String value) {
- sort = false;
- switch (index) {
- case 0 :setEveryPage(Long.parseLong(value));break;
- case 1 :first();break;
- case 2: previous();break;
- case 3: next();break;
- case 4: last();break;
- case 5: sort = true;sort(value);break;
- case 6 ://到指定第多少页
- setCurrentPage(Long.parseLong(value));
- break;
- }
- }
- /**
- * 最前一页
- */
- private void first() {
- currentPage = 1L;
- }
- private void previous() {
- currentPage--;
- }
- private void next() {
- currentPage++;
- }
- private void last() {
- currentPage = totalPage;
- }
- private void sort(String sortName) {
- //设置排序状态
- setPageSortState(sortName);
- }
- /**
- * 计算总页数
- * */
- private Long getTotalPage(Long totalRecords) {
- Long totalPage = 0L;
- if (totalRecords % everyPage == 0)
- totalPage = totalRecords / everyPage;
- else {
- totalPage = totalRecords / everyPage + 1;
- }
- return totalPage;
- }
- public Long getBeginIndex() {
- this.beginIndex = (currentPage - 1) * everyPage;
- return this.beginIndex;
- }
- public void setBeginIndex(Long beginIndex) {
- this.beginIndex = beginIndex;
- }
- public Long getCurrentPage() {
- this.currentPage = currentPage == 0 ? 1 : currentPage;
- return this.currentPage;
- }
- public void setCurrentPage(Long currentPage) {
- if(0 == currentPage){
- currentPage = 1L;
- }
- this.currentPage = currentPage;
- }
- public Long getEveryPage() {
- this.everyPage = everyPage == 0 ? 10 : everyPage;
- return this.everyPage;
- }
- public void setEveryPage(Long everyPage) {
- this.everyPage = everyPage;
- }
- public Boolean getHasNextPage() {
- this.hasNextPage = (currentPage != totalPage) && (totalPage != 0);
- return this.hasNextPage;
- }
- public void setHasNextPage(Boolean hasNextPage) {
- this.hasNextPage = hasNextPage;
- }
- public Boolean getHasPrePage() {
- this.hasPrePage = currentPage != 1;
- return this.hasPrePage;
- }
- public void setHasPrePage(Boolean hasPrePage) {
- this.hasPrePage = hasPrePage;
- }
- public Long getTotalPage() {
- return this.totalPage;
- }
- public void setTotalPage(Long totalPage) {
- if(this.currentPage > totalPage){
- this.currentPage = totalPage;
- }
- this.totalPage = totalPage;
- }
- public Long getTotalCount() {
- return this.totalCount;
- }
- public void setTotalCount(Long totalCount) {
- setTotalPage(getTotalPage(totalCount));
- this.totalCount = totalCount;
- }
- @Override
- public String toString() {
- return ToStringBuilder.reflectionToString(this);
- }
- /**
- * 设置排序状态
- * */
- private void setPageSortState(String newPageSortName){
- //判断之前的排序字段是否为空
- if(StringUtils.isEmpty(sortName)){
- //默认排序为升序
- this.sortState = PageUtil.ASC;
- this.sortInfo = PageUtil.PAGE_ASC;
- }else{
- if(StringUtils.equalsIgnoreCase(newPageSortName, sortName)){
- //判断sortState排序状态值
- if(StringUtils.equalsIgnoreCase(sortState, PageUtil.ASC)){
- this.sortState = PageUtil.DESC;
- this.sortInfo = PageUtil.PAGE_DESC;
- }else{
- this.sortState = PageUtil.ASC;
- this.sortInfo = PageUtil.PAGE_ASC;
- }
- }else{
- //默认
- this.sortState = PageUtil.ASC;
- this.sortInfo = PageUtil.PAGE_ASC;
- }
- }
- sortName = newPageSortName.toLowerCase();
- }
- public Boolean isSort() {
- return sort;
- }
- public void setSort(Boolean sort) {
- this.sort = sort;
- }
- public String getInitQuerySql() {
- return initQuerySql;
- }
- public void setInitQuerySql(String initQuerySql) {
- this.initQuerySql = initQuerySql;
- }
- public Long getEndinIndex() {
- this.endinIndex = (currentPage) * everyPage;
- return endinIndex;
- }
- public void setEndinIndex(Long endinIndex) {
- this.endinIndex = endinIndex;
- }
- }
2 PageState.java
- package com.liuzd.page;
- import org.apache.commons.lang3.StringUtils;
- /**
- * 分页状态类
- * @author liuzd
- * @version 1.0 2011-05-12
- * @since JDK1.5
- * */
- public enum PageState {
- /**
- * 设置每页显示多少条
- * */
- SETPAGE,
- /**
- * 首页
- * */
- FIRST,
- /**
- * 向前一页
- * */
- PREVIOUS,
- /**
- * 向后一页
- * */
- NEXT,
- /**
- * 末页
- * */
- LAST,
- /**
- * 排序
- * */
- SORT,
- /**
- * 到第多少页
- * */
- GOPAGE;
- /**
- * @param value 索引名称
- * @return 返回索引下标
- */
- public static int getOrdinal(String value) {
- int index = -1;
- if (StringUtils.isEmpty(value)) {
- return index;
- }
- String newValue = StringUtils.trim(value).toUpperCase();
- try {
- index = valueOf(newValue).ordinal();
- } catch (IllegalArgumentException e) {}
- return index;
- }
- }
3 PageUtil.java
- package com.liuzd.page;
- /**
- * 分页工具类
- * @author liuzd
- * @version 1.0 2011-05-12
- * @since JDK1.5
- * */
- public class PageUtil {
- public static final String ASC = "asc";
- public static final String DESC = "desc";
- public static final String PAGE_DESC = "↓";
- public static final String PAGE_ASC = "↑";
- public static final String PAGE_NULL = " ";
- public static final String SESSION_PAGE_KEY = "page";
- /**
- * @param querySql 查询SQL
- * @param beginIndex 开始下标
- * @param endinIndex 结束下标
- * @return
- */
- public static String getPageQuerySql(String querySql,Long beginIndex, Long endinIndex) {
- if(querySql.indexOf("where rn>") != -1 && querySql.indexOf("and rn<=") != -1){
- return querySql.toUpperCase();
- }
- return new java.lang.StringBuffer().append(querySql).append(" where rn>").append(beginIndex).append(" and rn<=").append(endinIndex).toString().toUpperCase();
- }
- /**
- * @param querySql 查询SQL
- * @param orderByName 排序列名
- * @return
- */
- @SuppressWarnings("unused")
- public static String createQuerySql(String querySql, String orderByName) {
- StringBuilder sql = new StringBuilder();
- sql.append("select ttt.* from(select tt.*,rownum rn from(");
- sql.append(querySql);
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderByName)) {
- sql.append(" order by ").append(orderByName);
- }
- sql.append(" )tt)ttt ");
- return sql.toString();
- }
- /**
- * 取得排序名称+desc or asc
- * @param querySql 查询SQL
- * @return 返回查询语句 SELECT ... FROM TABLE ORDER BY ID DESC 中的 ID DESC
- */
- public static String getSortDescOrAsc(String querySql) {
- /**取得ordery by之前的查询字符串*/
- querySql = querySql.toUpperCase();
- String temp = "ORDER BY";
- int orderIndex = querySql.lastIndexOf(temp);
- String newsql = querySql.substring(orderIndex);
- String temp2 = ")";
- int lastIndex = newsql.indexOf(temp2);
- String orderByName = newsql.substring(temp.length(),lastIndex).trim();
- return orderByName;
- }
- /**
- * 初始化分页类
- * @param initPageSql 未分页的查询SQL
- * @param totalCount 总行数
- * @param index 分页状态
- * @param value 只有在设置每页显示多少条时,值不会NULL,其它为NULL
- */
- public static Page inintPage(String initPageSql,Long totalCount,Integer index,String value,Page sessionPage){
- Page page = null;
- if(index < 0){
- page = new Page(totalCount);
- }else{
- /**每页显示多少条*/
- Long everPage = null == value ? 10 : Long.parseLong(value);
- /**获取Session中的分页类,方便保存页面分页状态*/
- page = sessionPage;
- page.setEveryPage(everPage);
- page.setTotalCount(totalCount);
- }
- page.setInitQuerySql(initPageSql);
- /**对查询SQL进行分页计算*/
- String querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
- /**真正传递到后台执行获取分页数据的sql*/
- page.setQuerySql(querySql);
- /**保存到Session中*/
- return page;
- }
- /**
- * 当页点击:首页,前一页,后一页,末页,排序,到第多少页时进行分页操作
- * @param index 分页状态
- * @param value 排序字段名或者到第多少页
- */
- public static Page execPage(int index,String value,Page sessionPage){
- Page page = sessionPage;
- /**调用方法进行分页计算*/
- page.pageState(index,value);
- /**未进行分页前的sql*/
- String initPageSql = page.getInitQuerySql();
- /**进行分页SQL组合*/
- String querySql = getPageQuerySql(initPageSql,page.getBeginIndex(), page.getEndinIndex());
- /**替换排序列名*/
- if (page.isSort() == true) {
- String sortName = page.getSortName();
- if (null != sortName) {
- /**获取排序状态:值(desc or asc)*/
- String descAsc = page.getSortState();
- /**组合新的排序字段与状态*/
- String sortNameDescAsc = (" " + sortName + " " + descAsc).toUpperCase();
- /**返回之前的排序字段与状态*/
- String getOldSortName = PageUtil.getSortDescOrAsc(querySql);
- /**返回最新的排序字段与状态*/
- querySql = querySql.replace(getOldSortName,sortNameDescAsc);
- }
- }
- page.setQuerySql(querySql);
- return page;
- }
- }
4 page.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
- <c:set var="page" value="${sessionScope.page}" />
- <c:set var="path" value="${pageContext.request.contextPath}" />
- <c:set var="url" value="${param.url}" />
- <c:set var="urlParams" value="${param.urlParams}" />
- <c:set var="pathurl" value="${path}/${url}" />
- <tr>
- <td colspan="5">
- 共${page.totalCount}条记录 共${page.totalPage}页 每页显示${page.everyPage}条
- 当前第${page.currentPage}页
- <c:choose>
- <c:when test="${page.hasPrePage eq false}">
- <<首页 <上页
- </c:when>
- <c:otherwise>
- <a href="${pathurl}?&pageAction=first${urlParams}"><<首页 </a>
- <a href="${pathurl}?pageAction=previous${urlParams}" /><上一页</a>
- </c:otherwise>
- </c:choose>
- ||
- <c:choose>
- <c:when test="${page.hasNextPage eq false}">
- 下页> 尾页>>
- </c:when>
- <c:otherwise>
- <a href="${pathurl}?&pageAction=next${urlParams}">下一页> </a>
- <a href="${pathurl}?pageAction=last${urlParams}" />末页>></a>
- </c:otherwise>
- </c:choose>
-
- <SELECT name="indexChange" id="indexChange"
- onchange="getCurrentPage(this.value);">
- <c:forEach var="index" begin="1" end="${page.totalPage}" step="1">
- <option value="${index}" ${page.currentPage eq index ? "selected" : ""}>
- 第${index}页
- </option>
- </c:forEach>
- </SELECT>
-
- 每页显示:<select name="everyPage" id="everyPage" onchange="setEveryPage(this.value);">
- <c:forEach var="pageCount" begin="5" end="${page.totalCount}" step="5">
- <option value="${pageCount}" ${page.everyPage eq pageCount ? "selected" : ""}>
- ${pageCount}条
- </option>
- </c:forEach>
- </select>
- </td>
- </tr>
- <div style='display: none'>
- <a class=listlink id="indexPageHref" href='#'></a>
- </div>
- <script>
- function getCurrentPage(index){
- var a = document.getElementById("indexPageHref");
- a.href = '${pathurl}?pageAction=gopage¤tPage='+index+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- function setEveryPage(everyPage){
- var a = document.getElementById("indexPageHref");
- var currentPage = document.getElementById('indexChange').value;
- a.href = '${pathurl}?pageAction=setpage&everyPage='+everyPage+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- function sortPage(sortName){
- var a = document.getElementById("indexPageHref");
- a.href = '${pathurl}?pageAction=sort&sortName='+sortName+'${urlParams}';
- a.setAttribute("onclick",'');
- a.click("return false");
- }
- </script>
- 原地址是 http://liuzidong.iteye.com/blog/1042172
SSH:Struts2.2+Hibernate3.6+Spring3.1分页示例[转]的更多相关文章
- ssh2项目整合 struts2.1+hibernate3.3+spring3 基于hibernate注解和struts2注解
项目文件夹结构例如以下: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW9uZ3poaWFu/font/5a6L5L2T/fontsize/400/fi ...
- SSh框架结构(Struts2.1+Hibernate4.0+Spring3.1)
一个.使用的工具 开发工具:My Eclipse 10.7以及对应的java开发工具 框架版本号:Struts2.1+Hibernate3+Spring3.0 数据库:MySql5.5 Mysql可视 ...
- SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>
此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...
- 工作笔记3.手把手教你搭建SSH(struts2+hibernate+spring)环境
上文中我们介绍<工作笔记2.软件开发经常使用工具> 从今天開始本文将教大家怎样进行开发?本文以搭建SSH(struts2+hibernate+spring)框架为例,共分为3步: 1)3个 ...
- Struts2.3.4.1+Spring3.2.3+Hibernate4.1.9整合
java教程|Struts2.3.4.1+Spring3.2.3+Hibernate4.1.9整合教程并测试成功一.创建项目二.搭建struts-2.3.4.11.struts2必须的Jar包(放到W ...
- ExtJs、Struts2、Hibernate3.2登录页面的简单实现
1.思想的大致模型 2.建立数据库test和数据库表tb_user 1 CREATEDATABASE `test`; 2 CREATETABLE `test`.`tb_user` ( 3 `user ...
- SQL Server 2012 OFFSET/FETCH NEXT分页示例(转载)
原文:http://beyondrelational.com/modules/29/presentations/483/scripts/12983/sql-server-2012-server-sid ...
- Struts2使用拦截器完成权限控制示例
http://aumy2008.iteye.com/blog/146952 Struts2使用拦截器完成权限控制示例 示例需求: 要求用户登录,且必须为指定用户名才可以查看系统中某个视图资源:否 ...
- SQL Server 2012 OFFSET/FETCH NEXT分页示例
原文:http://beyondrelational.com/modules/29/presentations/483/scripts/12983/sql-server-2012-server-sid ...
随机推荐
- sp 数据导入导出
https://msdn.microsoft.com/zh-cn/library/ee231568.aspxsharepoint 微软文档 sharepoint 导入导出分两种: 1.一个网站全部导入 ...
- IOS JSON
//请求数据 dispatch_async(dispatch_get_global_queue(, ), ^{ _dataArray=[NSMutableArray array]; NSString ...
- [OC][地图] 高德地图之定位初探(一)
使用前的说明 高德地图开放平台的iOS定位模块网址-->http://lbs.amap.com/api/ios-location-sdk/summary/ 高德地图有Web端.android平台 ...
- JFinal - scheduler 插件做定时任务
我在项目中遇到一个需求:服务运行期间,数据库要定期去监测某表并且更新. 正好项目是使用 jfinal 做的,于是就用了 jfinal-scheduler 插件来解决(jfinal-scheduler ...
- centos 怎么安装 g++
centos 怎么安装 g++ 找了n久 找到一个实用的 有gcc 但是 是老版本的 tarball 编译 nmap 的时候说机器没有g++ 各种方法都试过 然后 找到下面这个方法: cento ...
- About next_permutation
哈哈没错这个又是我们C++党的语言优势之一,用这个函数可以求当前排序的下一个排序,也就是说可以方便的求全排列,用这个函数需要用到algorithm这个头文件. 与这个函数相反的是prev_permut ...
- 利用Object.prototype.toString方法,实现比typeof更准确的type校验
Object.prototype.toString方法返回对象的类型字符串,因此可以用来判断一个值的类型. 调用方法: Object.prototype.toString.call(value) 不同 ...
- Java多线程总结之线程安全队列Queue
在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列.Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQueue,非 ...
- springmvc 解决跨域CORS
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...
- 转:OSGI 实战 Equinox
http://download.csdn.net/detail/ifmliuzhen/3231590