Struts2 实现翻页组件
来源:互联网 发布:微星淘宝买好还是京东 编辑:程序博客网 时间:2024/05/21 12:23
翻页组件的需求是:
1.首页,上一页,下一页,末页
2.总是显示当前页面的前两页和后两页的页码
如图:
以下是代码:
PageModel<T>
import java.util.List;/** * 分页组件 * @param <T> 实体对象 */public class PageModel<T> {private int totalRecords;// 总记录数private List<T> list;// 结果集// 当前页private Integer pageNo;// 每页显示多少条private Integer pageSize;/** * 取得上一页 * * @return 上一页 */public int getPreviousPageNo() {if (pageNo <= 1) {return 1;}return pageNo - 1;}/** * 取得下一页 * * @return 下一页 */public int getNextPageNo() {if (pageNo >= getTotalPages()) {return getTotalPages() == 0 ? 1 : getTotalPages();}return pageNo + 1;}/** * 取得最后一页 * * @return 最后一页 **/public int getBottomPageNo() {return getTotalPages() == 0 ? 1 : getTotalPages();}/** * 取得总页数 * * @return **/public int getTotalPages() {if (totalRecords % pageSize == 0) {return totalRecords / pageSize;} else {return totalRecords / pageSize + 1;}}public int getTotalRecords() {return totalRecords;}public void setTotalRecords(int totalRecords) {this.totalRecords = totalRecords;}public List<T> getList() {return list;}public void setList(List<T> list) {this.list = list;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}public Integer getPageNo() {return pageNo;}public void setPageNo(Integer pageNo) {this.pageNo = pageNo;}}
DaoSupport.java
package com.test.dao;import java.io.Serializable;import java.util.List;import java.util.Map;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.test.model.PageModel;import com.test.util.GenericsUtils;/** * Dao支持类 * @param <T> */@Transactional@SuppressWarnings("unchecked")public class DaoSupport<T> implements BaseDao<T>{ // 泛型的类型 protected Class<T> entityClass = GenericsUtils.getGenericType(this.getClass()); @Override public void delete(Serializable ... ids) { for (Serializable id : ids) { T t = (T) getSession().load(this.entityClass, id); getSession().delete(t); } } /** * 利用get()方法加载对象,获取对象的详细信息 */ @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public T get(Serializable entityId) { return (T) getSession().get(this.entityClass, entityId); } /** * 利用load()方法加载对象,获取对象的详细信息 */ @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public T load(Serializable entityId) { return (T) getSession().load(this.entityClass, entityId); } /** * 利用hql语句查找单条信息 */ @Override @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public Object uniqueResult(final String hql,final Object[] queryParams) { Query query=getSession().createQuery(hql); setQueryParams(query, queryParams);//设置查询参数 return query.uniqueResult(); } /** * 获取指定对象的信息条数 */ @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public long getCount() { String hql = "select count(*) from " + GenericsUtils.getGenericName(this.entityClass); return (Long)uniqueResult(hql,null); } /** * 利用save()方法保存对象的详细信息 */ @Override public void save(Object obj) { getSession().save(obj); } @Override public void saveOrUpdate(Object obj) { getSession().saveOrUpdate(obj); } /** * 利用update()方法修改对象的详细信息 */ @Override public void update(Object obj) { getSession().update(obj); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public PageModel<T> find(final Integer pageNo, Integer maxResult) { return find(null, null, null, pageNo, maxResult); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public PageModel<T> find(Integer pageNo, Integer maxResult, Map<String, String> orderby) { return find(null, null, orderby, pageNo, maxResult); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public PageModel<T> find(Integer pageNo, Integer maxResult, String where, Object[] queryParams) { return find(where, queryParams, null, pageNo, maxResult); } /** * 分页查询 * @param where 查询条件 * @param queryParams hql参数值 * @param orderby 排序 * @param pageNo 第几页 * @param maxResult 返回记录数量 * return PageModel */ @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public PageModel<T> find(final String where, final Object[] queryParams, final Map<String, String> orderby, final Integer pageNo, final Integer maxResult) { final PageModel<T> pageModel = new PageModel<T>();//实例化分页对象 pageModel.setPageNo(pageNo);//设置当前页数 pageModel.setPageSize(maxResult);//设置每页显示记录数 String hql = new StringBuffer().append("from ")//添加form字段 .append(GenericsUtils.getGenericName(entityClass))//添加对象类型 .append(" ")//添加空格 .append(where == null ? "" : where)//如果where为null就添加空格,反之添加where .append(createOrderBy(orderby))//添加排序条件参数 .toString();//转化为字符串 Query query = getSession().createQuery(hql);//执行查询 setQueryParams(query,queryParams);//为参数赋值 List<T> list = null;//定义List对象 // 如果maxResult<0,则查询所有 if(maxResult < 0 && pageNo < 0){ list = query.list();//将查询结果转化为List对象 }else{ list = query.setFirstResult(getFirstResult(pageNo, maxResult))//设置分页起始位置 .setMaxResults(maxResult)//设置每页显示的记录数 .list();//将查询结果转化为List对象 //定义查询总记录数的hql语句 hql = new StringBuffer().append("select count(*) from ")//添加hql语句 .append(GenericsUtils.getGenericName(entityClass))//添加对象类型 .append(" ")//添加空格 .append(where == null ? "" : where)//如果where为null就添加空格,反之添加where .toString();//转化为字符串 query = getSession().createQuery(hql);//执行查询 setQueryParams(query,queryParams);//设置hql参数 int totalRecords = ((Long) query.uniqueResult()).intValue();//类型转换 pageModel.setTotalRecords(totalRecords);//设置总记录数 } pageModel.setList(list);//将查询的list对象放入实体对象中//return null; return pageModel;//返回分页的实体对象 } /** * 获取分页查询中结果集的起始位置 * @param pageNo 第几页 * @param maxResult 页面显示的记录数 * @return 起始位置 */ protected int getFirstResult(int pageNo,int maxResult){ int firstResult = (pageNo-1) * maxResult; return firstResult < 0 ? 0 : firstResult; } /** * 对query中的参数赋值 * @param query * @param queryParams */ protected void setQueryParams(Query query, Object[] queryParams){ if(queryParams!=null && queryParams.length>0){ for(int i=0; i<queryParams.length; i++){ query.setParameter(i, queryParams[i]); } } } /** * 创建排序hql语句 * @param orderby * @return 排序字符串 */ protected String createOrderBy(Map<String, String> orderby){ StringBuffer sb = new StringBuffer(""); if(orderby != null && orderby.size() > 0){ sb.append(" order by "); for(String key : orderby.keySet()){ sb.append(key).append(" ").append(orderby.get(key)).append(","); } sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * 获取Session对象 * @return */ @Autowired @Qualifier("sessionFactory") private SessionFactory sessionFactory; protected Session getSession(){\ return sessionFactory.getCurrentSession(); }}
GenericsUtils.java
package com.test.util;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;/** * 泛型工具类 */public class GenericsUtils {/** * 获取泛型的类型 * @param clazz * @return Class */@SuppressWarnings("unchecked")public static Class getGenericType(Class clazz){Type genType = clazz.getGenericSuperclass();//得到泛型父类 Type[] types = ((ParameterizedType) genType).getActualTypeArguments();if (!(types[0] instanceof Class)) { return Object.class; } return (Class) types[0];}/** * 获取对象的类名称 * @param clazz * @return 类名称 */@SuppressWarnings("unchecked")public static String getGenericName(Class clazz){return clazz.getSimpleName();}}
NoticeDao.java
package com.test.dao.notice;import com.test.dao.BaseDao;import com.test.model.notice.Notice;public class NoticeDao extends BaseDao<Notice> {}
BaseAction.java
package com.test.action;import java.util.HashSet;import java.util.Map;import java.util.Set;import org.apache.struts2.interceptor.ApplicationAware;import org.apache.struts2.interceptor.RequestAware;import org.apache.struts2.interceptor.SessionAware;import org.springframework.beans.factory.annotation.Autowired;import com.opensymphony.xwork2.ActionSupport;/** * 基本Action对象,其它Action的父类 */public class BaseAction extends ActionSupport implements RequestAware,SessionAware, ApplicationAware {private static final long serialVersionUID = 1L;protected Integer id;protected Integer[] ids;protected Integer pageNo = 1;protected Integer pageSize = 5;public static final String LIST = "list";// 注入Dao@Autowiredprotected NoticeDao NoticeDao;// Map类型的requestprotected Map<String, Object> request;// Map类型的sessionprotected Map<String, Object> session;// Map类型的applicationprotected Map<String, Object> application;@Overridepublic void setRequest(Map<String, Object> request) {// 获取Map类型的request赋值this.request = request;}@Overridepublic void setApplication(Map<String, Object> application) {// 获取Map类型的application赋值this.application = application;}@Overridepublic void setSession(Map<String, Object> session) {// 获取Map类型的session赋值this.session = session;}// 处理方法public String execute() throws Exception {return SUCCESS;}// getter和settter方法public Integer[] getIds() {return ids;}public void setIds(Integer[] ids) {this.ids = ids;}public int getPageNo() {return pageNo;}public void setPageNo(int pageNo) {this.pageNo = pageNo;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}}
Notice.java
Notice.hbm.xml(省略)
package com.test.model.notice;import java.io.Serializable;import java.util.Date;/** */public class Notice implements Serializable{private static final long serialVersionUID = 1L;private Integer id;// 通知IDprivate String name;// 通知名称private String content;// 通知内容public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}
NoticeAction.java
import java.util.Date;import java.util.HashMap;import java.util.Map;import com.opensymphony.xwork2.ActionSupport;import com.test.action.BaseAction;import com.test.model.notice.Notice;/** * 通知Action */@Scope("prototype")@Controller("NoticeAction")public class NoticeAction extends BaseAction implements ModelDriven<Notice> {private static final long serialVersionUID = 1L;// 查询所有通知public String find() throws Exception {pageModel = noticeDao.find(pageNo, pageSize);// 执行查询方法return LIST;// 返回通知列表页面}private Notice notice = new Notice();private PageModel<Notice> pageModel;// 分页组件public Notice getNotice() {return notice;}public void setNotice(Notice notice) {this.notice = notice;}public PageModel<Notice> getPageModel() {return pageModel;}public void setPageModel(PageModel<Notice> pageModel) {this.pageModel = pageModel;}}
struts.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="notice" namespace="/notice"> <action name="notice_*" method="{1}" class="noticeAction"> <result name="list">/WEB-INF/pages/test/notice_list.jsp</result> <interceptor-ref name="adminDefaultStack"/> </action> </package> </struts>
查看通知列表:
<s:a action="notice_find" namespace="/notice">查看所有通知</s:a>
notice_list.jsp
<%@ 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>通知查看</title></head><body><table><thead><tr><th>ID</th><th>通知名称</th><th>通知内容</th></tr></thead><s:iterator value="pageModel.list"><tr><td><s:property value="id" /></td><td><s:property value="name" /></td><td><s:property value="content" /></td></tr></s:iterator></table> <ul class="pagination"> <s:if test="pageModel.pageNo > 1"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="1"></s:param><<</s:a></li> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo-1"></s:param>< </s:a></li> </s:if> <s:else> <li class="disabled"><a><<</a></li> <li class="disabled"><a><</a></li> </s:else> <s:if test="pageModel.pageNo > 2"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo-2"></s:param> <s:property value="pageModel.pageNo-2" /> </s:a></li> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo-1"></s:param> <s:property value="pageModel.pageNo-1" /> </s:a></li> </s:if> <s:if test="pageModel.pageNo == 2"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="1"></s:param>1</s:a></li> </s:if> <li class="active"><a><s:property value="pageModel.pageNo" /></a></li> <s:if test="pageModel.bottomPageNo - pageModel.pageNo > 1"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo+1"></s:param> <s:property value="pageModel.pageNo+1" /> </s:a></li> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo+2"></s:param> <s:property value="pageModel.pageNo+2" /> </s:a></li> </s:if> <s:if test="pageModel.bottomPageNo - pageModel.pageNo == 1"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo+1"></s:param> <s:property value="pageModel.bottomPageNo" /> </s:a></li> </s:if> <s:if test="pageModel.pageNo < pageModel.bottomPageNo"> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.pageNo+1"></s:param>> </s:a></li> <li><s:a action="notice_find" namespace="notice"> <s:param name="pageNo" value="pageModel.bottomPageNo"></s:param>>> </s:a></li> </s:if> <s:else> <li class="disabled"><a>></a></li> <li class="disabled"><a>>></a></li> </s:else> </ul></body></html>
1 0
- Struts2 实现翻页组件
- ICallbackEventHandler实现的无刷新翻页组件
- vue 实现 pager 组件翻页效果
- struts2中使用自定义标签实现翻页功能
- 简单的翻页组件
- js 翻页组件 pagination
- vue2.0翻页组件
- 自定义Struts2翻页标签
- CakePHP中使用Paginator组件(Helper)实现表格的翻页及排序
- 翻页功能的实现
- JDBC-ODBC实现翻页
- 键盘实现网页翻页
- 用PHP实现翻页
- ViewFlipper 实现翻页动画
- UIWebView 实现翻页功能
- PagerView实现翻页效果
- UIWebView 实现翻页功能
- 实现Ajax翻页效果
- org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'agoTime' in
- ES6
- MySql优化--慢查日志
- 使用SharedPreferences实现记住账号密码的功能
- CentOS安装配置Tomcat7
- Struts2 实现翻页组件
- ListIterator
- Oracle常用SQL
- Unity 编辑器下控制播放Animator
- DOM简介
- 第十周 项目1 - 二叉树算法库
- 第八周项目4 字符串加密
- 自定义AlertDialog实现下弹窗效果
- arcgis api for javascript 坐标转换