在ssh中实现分页排序
Posted 普通网友
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在ssh中实现分页排序相关的知识,希望对你有一定的参考价值。
ssh的分页排序
这个demo是我从平时的一个项目里提取出来的, 单独拿出来,供大家参考分页。
源码下载:https://pan.baidu.com/s/1s_Eex7dxIh-mUu88B1QA5A
提取码 cndl
实现效果
下面开始讲怎么实现
sping的配置文件路径不要写错,不然会加载404.
这是demo目录
spring配置文件
<?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-2.0.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/db_sushe?useUnicode=true&characterEncoding=utf-8">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/model/TStu.hbm.xml</value>
</list>
</property>
</bean>
<bean id="CommonDAO" class="com.dao.CommonDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="TStuDAO" class="com.dao.TStuDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="stuAction" class="com.action.stuAction" scope="prototype">
<property name="stuDAO">
<ref bean="TStuDAO" />
</property>
</bean>
</beans>
Struts的配置文件如下“”
<?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="liu" extends="struts-default">
<global-results>
<result name="succeed">/common/succeed.jsp</result>
<result name="successAdd">/common/add_success.jsp</result>
<result name="successDel">/common/del_success.jsp</result>
<result name="successUpdate">/common/update_success.jsp</result>
</global-results>
<!-- 学生用户 -->
<action name="stuMana" class="stuAction" method="stuMana">
<result name="success">/stuMana.jsp</result>
</action>
</package>
</struts>
stuAction.java:
package com.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import com.dao.TStuDAO;
import com.model.TStu;
import com.opensymphony.xwork2.ActionSupport;
public class stuAction extends ActionSupport
private int stuId;
private String stuXuehao;
private String stuRealname;
private String stuSex;
private String stuAge;
private String stuZhengzhimianmao;
private String stuCard;
private String loginName;
private String loginPw;
private String louhao;
private String sushehao;
private int searchType;
private int delType ;
private String delData;
private String message;
private String path;
private TStuDAO stuDAO;
private String filename;
private InputStream inputStream;
private static final int BUFFER_SIZE = 16 * 1024;
private File fujian;
private String fujianFileName;
public String stuMana()
List stuList = stuDAO.getHibernateTemplate().find(
"from TStu where del='no'");
Map request = (Map) ServletActionContext.getContext().get("request");
request.put("stuList", stuList);
return ActionSupport.SUCCESS;
public String getMessage()
return message;
public void setMessage(String message)
this.message = message;
public String getPath()
return path;
public void setInputStream(InputStream inputStream)
this.inputStream = inputStream;
public String getFilename()
return filename;
public File getFujian()
return fujian;
private static void copy(File src, File dst)
InputStream in = null;
OutputStream out = null;
try
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0)
out.write(buffer, 0, len);
catch (Exception e)
e.printStackTrace();
finally
if (null != in)
try
in.close();
catch (IOException e)
e.printStackTrace();
if (null != out)
try
out.close();
catch (IOException e)
e.printStackTrace();
public void setFujian(File fujian)
this.fujian = fujian;
public void setFilename(String filename)
this.filename = filename;
public TStuDAO getStuDAO()
return stuDAO;
public void setStuDAO(TStuDAO stuDAO)
this.stuDAO = stuDAO;
public void setPath(String path)
this.path = path;
public String getStuAge()
return stuAge;
public String getLoginName()
return loginName;
public void setLoginName(String loginName)
this.loginName = loginName;
public String getLoginPw()
return loginPw;
public void setLoginPw(String loginPw)
this.loginPw = loginPw;
public void setStuAge(String stuAge)
this.stuAge = stuAge;
public String getStuCard()
return stuCard;
public void setStuCard(String stuCard)
this.stuCard = stuCard;
public int getStuId()
return stuId;
public void setStuId(int stuId)
this.stuId = stuId;
public String getStuRealname()
return stuRealname;
public void setStuRealname(String stuRealname)
this.stuRealname = stuRealname;
public String getStuSex()
return stuSex;
public void setStuSex(String stuSex)
this.stuSex = stuSex;
public String getStuXuehao()
return stuXuehao;
public void setStuXuehao(String stuXuehao)
this.stuXuehao = stuXuehao;
public String getFujianFileName()
return fujianFileName;
public void setFujianFileName(String fujianFileName)
this.fujianFileName = fujianFileName;
public String getStuZhengzhimianmao()
return stuZhengzhimianmao;
public void setStuZhengzhimianmao(String stuZhengzhimianmao)
this.stuZhengzhimianmao = stuZhengzhimianmao;
public String getLouhao()
return louhao;
public void setLouhao(String louhao)
this.louhao = louhao;
public String getSushehao()
return sushehao;
public void setSushehao(String sushehao)
this.sushehao = sushehao;
public int getSearchType()
return searchType;
public void setSearchType(int searchType)
this.searchType = searchType;
public int getDelType()
return delType;
public void setDelType(int delType)
this.delType = delType;
public String getDelData()
return delData;
public void setDelData(String delData)
this.delData = delData;
CommonDAO.java
package com.dao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.util.Info;
/**
* A data access object (DAO) providing persistence and search support for Txl
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.cz.entity.Txl
* @author MyEclipse Persistence Tools
*/
public class CommonDAO extends HibernateDaoSupport
private static final Log log = LogFactory.getLog(CommonDAO.class);
protected void initDao()
// do nothing
public void save(Object transientInstance)
try
getHibernateTemplate().save(transientInstance);
catch (RuntimeException re)
throw re;
public void delete(Object persistentInstance)
try
getHibernateTemplate().delete(persistentInstance);
catch (RuntimeException re)
throw re;
public Object findById(int id,String entity)
try
Object instance = getHibernateTemplate().get("com.model."+entity, id);
return instance;
catch (RuntimeException re)
throw re;
public Object findById(String id,String entity)
try
Object instance = getHibernateTemplate().get("com.model."+entity, Integer.parseInt(id) );
return instance;
catch (RuntimeException re)
throw re;
public List findByHql(String hql)
try
return getHibernateTemplate().find(hql);
catch (RuntimeException re)
throw re;
public List findByHql(String hql,int dpage,int rows)
try
List list = getHibernateTemplate().find(hql);
List mlist=new ArrayList();
try
int min = (dpage-1)*rows;
int max = dpage*rows;
for(int i=0;i<list.size();i++)
if(!(i<min||i>(max-1)))
mlist.add(list.get(i));
catch(RuntimeException re)
re.printStackTrace();
throw re;
return mlist;
catch (RuntimeException re)
throw re;
public Object update(Object detachedInstance)
try
getHibernateTemplate().merge(detachedInstance);
return null;
catch (RuntimeException re)
throw re;
public void delete(int id,String entity)
System.out.println("cc="+id);
try
getHibernateTemplate().delete(getHibernateTemplate().get("com.model."+entity, id));
catch (RuntimeException re)
throw re;
public void delete(String id,String entity)
System.out.println("cc="+id);
try
getHibernateTemplate().delete(getHibernateTemplate().get("com.model."+entity, Integer.parseInt(id) ));
catch (RuntimeException re)
throw re;
public static CommonDAO getFromApplicationContext(ApplicationContext ctx)
return (CommonDAO) ctx.getBean("CommonDAO");
TStuDAO.java
package com.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.model.TStu;
/**
* Data access object (DAO) for domain model class TStu.
*
* @see com.model.TStu
* @author MyEclipse Persistence Tools
*/
public class TStuDAO extends HibernateDaoSupport
private static final Log log = LogFactory.getLog(TStuDAO.class);
// property constants
public static final String STU_XUEHAO = "stuXuehao";
public static final String STU_REALNAME = "stuRealname";
public static final String STU_SEX = "stuSex";
public static final String STU_AGE = "stuAge";
public static final String STU_CARD = "stuCard";
public static final String STU_ZHENGZHIMIANMAO = "stuZhengzhimianmao";
public static final String LOGIN_NAME = "loginName";
public static final String LOGIN_PW = "loginPw";
public static final String DEL = "del";
protected void initDao()
// do nothing
public void save(TStu transientInstance)
log.debug("saving TStu instance");
try
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
catch (RuntimeException re)
log.error("save failed", re);
throw re;
public void delete(TStu persistentInstance)
log.debug("deleting TStu instance");
try
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
catch (RuntimeException re)
log.error("delete failed", re);
throw re;
public TStu findById(java.lang.Integer id)
log.debug("getting TStu instance with id: " + id);
try
TStu instance = (TStu) getHibernateTemplate().get("com.model.TStu",
id);
return instance;
catch (RuntimeException re)
log.error("get failed", re);
throw re;
public List findByExample(TStu instance)
log.debug("finding TStu instance by example");
try
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
catch (RuntimeException re)
log.error("find by example failed", re);
throw re;
public List findByProperty(String propertyName, Object value)
log.debug("finding TStu instance with property: " + propertyName
+ ", value: " + value);
try
String queryString = "from TStu as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
catch (RuntimeException re)
log.error("find by property name failed", re);
throw re;
public List findByStuXuehao(Object stuXuehao)
return findByProperty(STU_XUEHAO, stuXuehao);
public List findByStuRealname(Object stuRealname)
return findByProperty(STU_REALNAME, stuRealname);
public List findByStuSex(Object stuSex)
return findByProperty(STU_SEX, stuSex);
public List findByStuAge(Object stuAge)
return findByProperty(STU_AGE, stuAge);
public List findByStuCard(Object stuCard)
return findByProperty(STU_CARD, stuCard);
public List findByStuZhengzhimianmao(Object stuZhengzhimianmao)
return findByProperty(STU_ZHENGZHIMIANMAO, stuZhengzhimianmao);
public List findByLoginName(Object loginName)
return findByProperty(LOGIN_NAME, loginName);
public List findByLoginPw(Object loginPw)
return findByProperty(LOGIN_PW, loginPw);
public List findByDel(Object del)
return findByProperty(DEL, del);
public List findAll()
log.debug("finding all TStu instances");
try
String queryString = "from TStu";
return getHibernateTemplate().find(queryString);
catch (RuntimeException re)
log.error("find all failed", re);
throw re;
public TStu merge(TStu detachedInstance)
log.debug("merging TStu instance");
try
TStu result = (TStu) getHibernateTemplate().merge(detachedInstance);
log.debug("merge successful");
return result;
catch (RuntimeException re)
log.error("merge failed", re);
throw re;
public void attachDirty(TStu instance)
log.debug("attaching dirty TStu instance");
try
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
catch (RuntimeException re)
log.error("attach failed", re);
throw re;
public void attachClean(TStu instance)
log.debug("attaching clean TStu instance");
try
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
catch (RuntimeException re)
log.error("attach failed", re);
throw re;
public static TStuDAO getFromApplicationContext(ApplicationContext ctx)
return (TStuDAO) ctx.getBean("TStuDAO");
下面是moder层都是一些字段映射(简单)
TStu.java
package com.model;
/**
* TStu generated by MyEclipse Persistence Tools
*/
public class TStu implements java.io.Serializable
// Fields
private Integer stuId;
private String stuXuehao;
private String stuRealname;
private String stuSex;
private String stuAge;
private String stuCard;
private String stuZhengzhimianmao;
private String loginName;
private String loginPw;
private String louhao;
private String sushehao;
private String del;
// Constructors
/** default constructor */
public TStu()
/** full constructor */
public TStu(String stuXuehao, String stuRealname, String stuSex,
String stuAge, String stuCard, String stuZhengzhimianmao,
String loginName, String loginPw, String del)
this.stuXuehao = stuXuehao;
this.stuRealname = stuRealname;
this.stuSex = stuSex;
this.stuAge = stuAge;
this.stuCard = stuCard;
this.stuZhengzhimianmao = stuZhengzhimianmao;
this.loginName = loginName;
this.loginPw = loginPw;
this.del = del;
// Property accessors
public Integer getStuId()
return this.stuId;
public void setStuId(Integer stuId)
this.stuId = stuId;
public String getStuXuehao()
return this.stuXuehao;
public void setStuXuehao(String stuXuehao)
this.stuXuehao = stuXuehao;
public String getStuRealname()
return this.stuRealname;
public void setStuRealname(String stuRealname)
this.stuRealname = stuRealname;
public String getStuSex()
return this.stuSex;
public void setStuSex(String stuSex)
this.stuSex = stuSex;
public String getStuAge()
return this.stuAge;
public void setStuAge(String stuAge)
this.stuAge = stuAge;
public String getStuCard()
return this.stuCard;
public void setStuCard(String stuCard)
this.stuCard = stuCard;
public String getStuZhengzhimianmao()
return this.stuZhengzhimianmao;
public void setStuZhengzhimianmao(String stuZhengzhimianmao)
this.stuZhengzhimianmao = stuZhengzhimianmao;
public String getLoginName()
return this.loginName;
public void setLoginName(String loginName)
this.loginName = loginName;
public String getLoginPw()
return this.loginPw;
public void setLoginPw(String loginPw)
this.loginPw = loginPw;
public String getDel()
return this.del;
public void setDel(String del)
this.del = del;
public String getLouhao()
return louhao;
public void setLouhao(String louhao)
this.louhao = louhao;
public String getSushehao()
return sushehao;
public void setSushehao(String sushehao)
this.sushehao = sushehao;
TStu.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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.model.TStu" table="t_stu">
<id name="stuId" type="java.lang.Integer">
<column name="stu_id" />
<generator class="increment" />
</id>
<property name="stuXuehao" type="java.lang.String">
<column name="stu_xuehao" length="50" />
</property>
<property name="stuRealname" type="java.lang.String">
<column name="stu_realname" length="50" />
</property>
<property name="stuSex" type="java.lang.String">
<column name="stu_sex" length="50" />
</property>
<property name="stuAge" type="java.lang.String">
<column name="stu_age" length="50" />
</property>
<property name="stuCard" type="java.lang.String">
<column name="stu_card" length="50" />
</property>
<property name="stuZhengzhimianmao" type="java.lang.String">
<column name="stu_zhengzhimianmao" length="50" />
</property>
<property name="loginName" type="java.lang.String">
<column name="login_name" length="50" />
</property>
<property name="loginPw" type="java.lang.String">
<column name="login_pw" length="50" />
</property>
<property name="del" type="java.lang.String">
<column name="del" length="50" />
</property>
<property name="louhao" type="java.lang.String">
<column name="louhao" length="50" />
</property>
<property name="sushehao" type="java.lang.String">
<column name="sushehao" length="50" />
</property>
</class>
</hibernate-mapping>
下面开始工具类com.util
Info.java
package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class Info
public static Object getDao(HttpServletRequest request,String name)
Object ad= (Object) WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getSession().getServletContext()).getBean(name);
return ad;
public synchronized static String getID()
Random random = new Random();
StringBuffer ret = new StringBuffer(20);
String rand = String.valueOf(Math.abs(random.nextInt()));
ret.append(getDateStr());
ret.append(rand.substring(0,6));
return ret.toString();
public synchronized static String subStr(String source,int length)
if(source.length()>length)
source=source.substring(0,length)+"...";
return source;
public static String getDateStr()
String dateString="";
try//yyyyMMddHHmmss
java.text.SimpleDateFormat formatter=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date currentTime_1=new java.util.Date();
dateString=formatter.format(currentTime_1);
catch(Exception e)
return dateString;
public static String getAutoId()
String dateString="";
try//yyyyMMddHHmmss
java.text.SimpleDateFormat formatter=new java.text.SimpleDateFormat("MMddhhmmss");
java.util.Date currentTime_1=new java.util.Date();
dateString=formatter.format(currentTime_1);
catch(Exception e)
return dateString;
public static String GetTheYear()
String dateString="";
try//yyyyMMddHHmmss
java.text.SimpleDateFormat formatter=new java.text.SimpleDateFormat("yyyy");
java.util.Date currentTime_1=new java.util.Date();
dateString=formatter.format(currentTime_1);
catch(Exception e)
return dateString;
public static void main(String[] g )
System.out.print(Info.getDateStr().substring(0, 10));
public static String getUTFStr(String str)
if(str==null)
return "";
try
str = new String(str.getBytes("ISO-8859-1"),"utf-8");
catch (UnsupportedEncodingException e)
// TODO Auto-generated catch block
e.printStackTrace();
return str;
public static String getGBKStr(String str) throws UnsupportedEncodingException
if(str==null)
return "";
return new String(str.getBytes("ISO-8859-1"),"GBK");
public static String getGB2312Str(String str) throws UnsupportedEncodingException
if(str==null)
return "";
return new String(str.getBytes("ISO-8859-1"),"gb2312");
/**
*得到多少天之后之前的日期��
* @param String date
* @param int day
* @return
*/
public static String getDay(String date,int day)
String b = date.substring(0,10);
String c = b.substring(0,4);
String d = b.substring(5,7);
String f = b.substring(8,10);
String aa = c+"/"+d+"/"+f;
String a = "";
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
GregorianCalendar grc=new GregorianCalendar();
grc.setTime(new Date(aa));
grc.add(GregorianCalendar.DAY_OF_MONTH,day);
String resu = dateFormat.format(grc.getTime());
String t[]= resu.split("-");
String sesuu = "";
for(int i=0;i<t.length;i++)
if(t[i].length()==1)
t[i]="0"+t[i];
sesuu += t[i]+"-";
return sesuu.substring(0,10);
/**
* 计算两个时期之间的天数
*
*/
public static int dayToday(String DATE1, String DATE2)
int i = 0;
DATE1 = DATE1.substring(0,DATE1.indexOf(" "));
DATE2 = DATE2.substring(0,DATE2.indexOf(" "));
String[] d1 = DATE1.split("-");
if(d1[1].length()==1)
DATE1 = d1[0]+"-0"+d1[1];
else
DATE1 = d1[0]+"-"+d1[1];
if(d1[2].length()==1)
DATE1 = DATE1+"-0"+d1[2];
else
DATE1 = DATE1+"-"+d1[2];
String[] d2 = DATE2.split("-");
if(d2[1].length()==1)
DATE2 = d2[0]+"-0"+d2[1];
else
DATE2 = d2[0]+"-"+d2[1];
if(d2[2].length()==1)
DATE2 = DATE2+"-0"+d2[2];
else
DATE2 = DATE2+"-"+d2[2];
for(int j=0;j<10000;j++)
i=j;
String gday = Info.getDay(DATE1, j);
if(gday.equals(DATE2))
break;
return i;
/**
* 比较时间大小
*
*/
public static String compare_datezq(String DATE1, String DATE2)
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime())
return "big";
else if (dt1.getTime() < dt2.getTime())
return "small";
else
return "den";
catch (Exception exception)
exception.printStackTrace();
return "den";
/**
* 过滤html代码
*
*/
public static String filterStrIgnoreCase(String source, String from, String to)
String sourceLowcase=source.toLowerCase();
String sub1,sub2,subLowcase1,subLowcase2;
sub1=sub2=subLowcase1=subLowcase2="";
int start=0,end;
boolean done=true;
if(source==null) return null;
if(from==null||from.equals("")||to==null||to.equals(""))
return source;
while(done)
start=sourceLowcase.indexOf(from,start);
if(start==-1)
break;
subLowcase1=sourceLowcase.substring(0,start);
sub1=source.substring(0,start);
end=sourceLowcase.indexOf(to,start);
if(end==-1)
end=sourceLowcase.indexOf("/>",start);
if(end==-1)
done=false;
else
end=end+to.length();
subLowcase2=sourceLowcase.substring(end,source.length());
sub2=source.substring(end,source.length());
sourceLowcase=subLowcase1+subLowcase2;
source=sub1+sub2;
//System.out.println(start+" "+end);
return source.replaceAll(" ", "");
public static void delPic(String path,String img)
if(img!=null)
if(!img.equals(""))
File file1=new File(path + "/" + img);
if(file1.exists() )
file1.deleteOnExit();
file1.delete();
这个是排序工具类ListSortUtil.java(是安装字段属性值进行排序,比如表中有userid,username,userpwd),可以按照表中任何一个属性值进行排序,排序规则如下:
package com.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.lang.reflect.Method;
public class ListSortUtil<T>
/**
* @param targetList 目标排序List
* @param sortField 排序字段(实体类属性名)
* @param sortMode 排序方式(asc or desc)
*/
@SuppressWarnings( "unchecked", "rawtypes" )
public void sort(List<T> targetList, final String sortField, final String sortMode)
Collections.sort(targetList, new Comparator()
public int compare(Object obj1, Object obj2)
int retVal = 0;
try
//首字母转大写
String newStr=sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\\\w","");
String methodStr="get"+newStr;
Method method1 = ((T)obj1).getClass().getMethod(methodStr, null);
Method method2 = ((T)obj2).getClass().getMethod(methodStr, null);
if (sortMode != null && "desc".equals(sortMode))
retVal = method2.invoke(((T) obj2), null).toString().compareTo(method1.invoke(((T) obj1), null).toString()); // 倒序
else
retVal = method1.invoke(((T) obj1), null).toString().compareTo(method2.invoke(((T) obj2), null).toString()); // 正序
catch (Exception e)
throw new RuntimeException();
return retVal;
);
PageManager.java分页工具类
package com.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.dao.CommonDAO;
public class PageManager
private PageManager()
// 默认一页最大记录数
public static final int DEFAULTPAGESIZE = 20;
// 分页段
public static final int segment = 10;
// 当前页数
protected int currentPage;
// 一页长度
protected int pageSize;
// 总页数
protected long pageNumber;
// 总记录数
protected long count;
// 数据
protected Collection collection;
// 数据查询对象
protected CommonDAO dao ;;
// 表现层代码
protected String info;
// 请求路径
protected String path;
// 服务器请求对象
protected HttpServletRequest request;
/*
* 仅仅只是加到路径中去
*/
protected String parameter = "";
/**
*
* @param 下一页的分页链接
* @param 一页最大记录数
* @param 当前HttpServletRequest对象
* @param 数据库操作对象
*/
protected PageManager(String path, int pageSize, HttpServletRequest request)
// 任意一个dao都行
this.dao = (CommonDAO)Info.getDao(request, "CommonDAO");
this.currentPage = 1;
this.pageNumber = 1;
this.count = 0;
this.pageSize = pageSize <= 0 ? DEFAULTPAGESIZE : pageSize;
this.request = request;
this.path = path;
request.setAttribute("page", this);
try
this.currentPage = Integer.parseInt(request
.getParameter("currentPage")) <= 0 ? 1 : Integer
.parseInt(request.getParameter("currentPage"));
catch (Exception e)
try
this.currentPage = Integer.parseInt((String) request
.getSession().getAttribute("currentPage"));
catch (Exception e1)
this.currentPage = 1;
/**
*
* @param 下一页的分页链接
* @param 一页最大记录数
* @param 当前HttpServletRequest对象
* @param 数据库操作对象
*/
public static PageManager getPage(String path, int pageSize,
HttpServletRequest request)
return new PageManager(path, pageSize, request);
/**
*
*
* @param hql语句
*
*/
public void doList(String hql)
this.count = this.dao.findByHql(hql).size();
if (this.count != 0)
this.pageNumber = count % this.pageSize == 0 ? this.count
/ this.pageSize : this.count / this.pageSize + 1;
if (this.currentPage > this.pageNumber)
this.currentPage = (int) this.pageNumber;
this.request.getSession().setAttribute("currentPage",
String.valueOf(this.currentPage));
this.collection = this.dao.findByHql(hql,
this.currentPage , this.pageSize);
this.refreshUrl();
/**
*
* @param 查询条件集合
* 如没有条件只是列表就不使用这个方法
*/
public void addParameter(List parameter)
StringBuffer para = new StringBuffer("");
if (parameter != null && parameter.size() != 0)
Iterator iterator = parameter.iterator();
while (iterator.hasNext())
para.append("&").append(iterator.next().toString());
this.parameter = para.toString();
/**
* 刷新分页路径
*
*/
protected void refreshUrl()
StringBuffer buf = new StringBuffer();
buf.append("<font color='#1157B7'>共").append(count);
buf.append("条");
buf.append(" ");
buf.append("第").append(this.currentPage).append("/").append(
this.pageNumber).append("页");
buf.append(" ");
if (this.currentPage == 1)
buf.append("首页");
else
buf.append("<a href='").append(this.path).append("¤tPage=1")
.append(parameter)
.append("' class='ls'>").append("首页")
.append("</a>");
// #1157B7
buf.append(" ");
if (this.currentPage > 1)
buf.append("<a href='").append(this.path).append("¤tPage=")
.append(currentPage - 1).append(parameter).append(
"' class='ls'>").append("上页")
.append("</a>");
else
buf.append("上页");
buf.append(" ");
int currentSegment = this.currentPage % segment == 0 ? this.currentPage
/ segment : this.currentPage / segment + 1;
/*for (int i = 1; i <= this.pageNumber; i++)
if (this.currentPage == i)
buf.append("<font color='red'>").append(i).append("</font>");
else
buf.append("<a href='").append(this.path).append(
"¤tPage=").append(i).append(parameter).append(
"' class='ls'>[").append(i).append(
"]</a>");
*/
buf.append(" ");
if (this.currentPage < this.pageNumber)
buf.append("<a href='").append(this.path).append("¤tPage=")
.append(currentPage + 1).append(parameter).append(
"' class='ls'>").append("下页")
.append("</a>");
else
buf.append("下页");
buf.append(" ");
if (this.currentPage == this.pageNumber)
buf.append("末页 ");
else
buf.append("<a href='").append(this.path).append("¤tPage=")
.append(this.pageNumber).append(parameter).append(
"' class='ls'>").append("末页")
.append("</a></font> ");
//
// for (int i = 0; i < this.pageNumber; i++)
// if (this.currentPage == i + 1)
// buf.append("<font color=red>[" + (i + 1) + "]</font>").append(
// " ");
// else
// buf.append("<a href='").append(this.path).append(
// "¤tPage=").append(i + 1).append(parameter)
// .append("' style='TEXT-DECORATION:none'>").append(
// "[" + (i + 1) + "]").append("</a> ");
//
//
buf.append("<select onchange=\\"javascript:window.location='").append(
this.path).append("¤tPage='+").append(
"this.options[this.selectedIndex].value").append(parameter)
.append("\\">");
for (int i = 0; i < this.pageNumber; i++)
if (this.currentPage == i + 1)
buf.append("<option value=" + (i + 1)
+ " selected=\\"selected\\">" + (i + 1) + "</option>");
else
buf.append("<option value=" + (i + 1) + ">" + (i + 1)
+ "</option>");
buf.append("</select>");
this.info = buf.toString();
public Collection getCollection()
return collection;
public long getCount()
return count;
public int getCurrentPage()
return currentPage;
public long getPageNumber()
return pageNumber;
public int getPageSize()
return pageSize;
public String getInfo()
return info;
最后就是页面展示和加载index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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>
<a href="<%=path %>/stuMana.action">学生排序分页</a>
</body>
</html>
stuMana.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@page import="com.dao.CommonDAO"%>
<%@page import="com.util.Info"%>
<%@page import="com.util.PageManager"%>
<%@page import="com.dao.CommonDAO"%>
<%@page import="com.util.Info"%>
<%@page import="com.model.TStu"%>
<%@page import="com.util.*"%>
<%@page import="com.util.PageManager"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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="<%=path %>/css/base.css" />
<script language="javascript">
function stuDel(stuId)
if(confirm('您确定删除吗?'))
window.location.href="<%=path %>/stuDel.action?stuId="+stuId;
function stuEditPre(stuId)
window.location.href="<%=path %>/stuEditPre.action?stuId="+stuId;
function stuAdd()
var url="<%=path %>/admin/stu/stuAdd.jsp";
//var n="";
//var w="480px";
//var h="500px";
//var s="resizable:no;help:no;status:no;scroll:yes";
//openWin(url,n,w,h,s);
window.location.href=url;
function daochu()
var url="<%=path %>/stuDaochu.action";
window.open(url,"_self");
function daoru()
document.getElementById("liu").style.display="block";
</script>
</head>
<body leftmargin="2" topmargin="2" background='<%=path %>/images/allbg.gif'>
<script type="text/javascript">
function exportExcel()
window.open('stuMana.action?exportToExcel=YES');
</script>
<!-- 显示网格线 -->
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>工作表标题</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo />
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<!-- 显示网格线 -->
<script type="text/javascript" src="../js/js.js"></script>
</HEAD>
<%
String exportToExcel = request.getParameter("exportToExcel");
if (exportToExcel != null
&& exportToExcel.toString().equalsIgnoreCase("YES"))
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "inline; filename="
+ "student.xls");
%>
<br/><br/>
<table width="98%" border="0" cellpadding="2" cellspacing="1" bgcolor="#D1DDAA" align="center" style="margin-top:8px">
<tr bgcolor="#E7E7E7">
<td height="14" colspan="10" background="<%=path %>/images/tbg.gif"> 学生管理 </td>
</tr>
<tr align="center" bgcolor="#FAFAF1" height="22">
<td width="10%">学号</td>
<td width="10%">姓名</td>
<td width="10%">性别</td>
<td width="10%">学院</td>
<td width="10%">班级</td>
<td width="10%">楼号</td>
<td width="10%">宿舍号</td>
<td width="10%">登陆账号</td>
<td width="10%">登录密码</td>
<td width="10%">操作</td>
</tr>
<%
CommonDAO dao = (CommonDAO)Info.getDao(request,"CommonDAO");
String hql = "from TStu where 1=1 "; //week(savetime) = week(now())
String url = "stuMana.action?1=1";
System.out.println(hql);
PageManager pageManager = PageManager.getPage(url,3, request);
pageManager.doList(hql);
PageManager bean= (PageManager)request.getAttribute("page");
ArrayList<TStu> startlist=( ArrayList<TStu>)bean.getCollection();
ArrayList<TStu> tzlist = new ArrayList<TStu>();
for(TStu startTzinfo:startlist)
ArrayList htlist = (ArrayList)dao.findByHql("from TStu where stuId="+startTzinfo.getStuId());
//startTzinfo.setHtnum(String.valueOf(htlist.size()));
tzlist.add(startTzinfo);
System.out.println("排序前:" +startlist);
System.out.println("tzlist=="+tzlist.size());
ListSortUtil<TStu> sortList = new ListSortUtil<TStu>();
//排序字段 userId
sortList.sort(tzlist, "stuRealname", "desc"); //排序规则进行升序
System.out.println("排序后:" +tzlist);
for(TStu tz:startlist)
%>
<s:iterator value="#request.stuList" id="stu">
<tr align='center' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='red';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="22">
<td bgcolor="#FFFFFF" align="center">
<%=tz.getStuXuehao()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getStuRealname()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getStuSex()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getStuZhengzhimianmao()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getStuCard()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getLouhao()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getSushehao()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getLoginName()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<%=tz.getLoginPw()%>
</td>
<td bgcolor="#FFFFFF" align="center">
<a href="#" onclick="stuEditPre( <%=tz.getStuId()%>)" class="pn-loperator">修改</a>
<a href="#" onclick="stuDel(<%=tz.getStuId()%>)" class="pn-loperator">删除</a>
</td>
</tr>
</s:iterator>
<% %>
</table>
<div style="text-align: center">
<div >
<div id="LAY_page">$page.info </div>
</div>
</div>
<table width='98%' border='0'style="margin-top:8px;margin-left: 5px;">
<tr>
<td>
<input type="button" value="添加" style="width: 80px;" onclick="stuAdd()" />
</td>
</tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr>
<td>
<a href="javascript:exportExcel();" style="width: 80px;"><h3> <font style="color: red">EXCEL批量导出</font></h3></a>
</td>
</tr>
</table>
</body>
</html>
实现效果:
源码下载:https://pan.baidu.com/s/1s_Eex7dxIh-mUu88B1QA5A
提取码 cndl
以上是关于在ssh中实现分页排序的主要内容,如果未能解决你的问题,请参考以下文章