分页程序是web不可缺少的功能,下面讲一下如何在ssh下创建分页程序。
1.创建结果集的顺序队列Page类
该类中的重点方法都已加上注释。
2.创建实体类User
3.创建DAO操作基类,该类中包含HibernateTemplate注入参数以及常用DAO数据操作方法,当然包含最重要的findByPage方法,代码如下:
4.创建UserDAO
5.创建UserDAOImpl
7.创建Action在子类中只要继承BaseAction类就行了
8.配置Struts2参数
9.前台post方法jsp页面:
10.创建common.js
10.创建get方式jsp文件
Ok.全部文件操作完成,下面打开tomcat进行测试。测试地址
http://127.0.0.1:8080/pager/u!userlist.action
http://127.0.0.1:8080/pager/u!getlist.action
该分页在优点为:pager的功能配置都在基类,子类使用分页功能极容易,方便进行开发。
缺点:功能复杂
程序源码:点击打开链接
1.创建结果集的顺序队列Page类
package com.bjsxt.registration.util;
import java.util.AbstractList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.RandomAccess;
/**
* 结果集的顺序队列
*/
@SuppressWarnings("unchecked")
public class Page<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private int currentPage;
private int pageNum; //
private int numPerPage; //每页显示多少条
private int totalCount; //总条数
private int totalPage; //总行数
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getNumPerPage() {
return numPerPage;
}
public void setNumPerPage(int numPerPage) {
this.numPerPage = numPerPage;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
private static final long serialVersionUID = 8683452581122892189L;
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
* 对象数组
*/
private transient E[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
* 类集的长度
*
* @serial
*/
private int size;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list.
* @exception IllegalArgumentException if the specified initial capacity
* is negative
* 开辟初始空间
*/
public Page(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = (E[])new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public Page() {
this(10);
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator. The <tt>ArrayList</tt> instance has an initial capacity of
* 110% the size of the specified collection.
*
* @param c the collection whose elements are to be placed into this list.
* @throws NullPointerException if the specified collection is null.
*/
public Page(Collection<? extends E> c) {
size = c.size();
// Allow 10% room for growth //10%作为增量
int capacity = (int) Math.min((size*110L)/100, Integer.MAX_VALUE);
elementData = (E[]) c.toArray(new Object[capacity]);
}
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
* 当对象数组大于对象类集时,根据对象类集缩放对象数组(把对象数组减至最低)
*/
public void trimToSize() {
modCount++;
int oldCapacity = elementData.length; //对象数组 大小
if (size < oldCapacity) {
Object oldData[] = elementData;
elementData = (E[])new Object[size];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity.
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length; //对象数组
if (minCapacity > oldCapacity) { //新数组尺寸大于对象数组尺寸
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1; //增容,算法:1.5*capacity+1
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = (E[])new Object[newCapacity];
System.arraycopy(oldData, 0, elementData, 0, size); //执行拷贝
}
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list.
*/
public int size() {
return size;
}
/**
* Tests if this list has no elements.
*
* @return <tt>true</tt> if this list has no elements;
* <tt>false</tt> otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns <tt>true</tt> if this list contains the specified element.
*
* @param elem element whose presence in this List is to be tested.
* @return <code>true</code> if the specified element is present;
* <code>false</code> otherwise.
*/
public boolean contains(Object elem) {
return indexOf(elem) >= 0;
}
/**
* Searches for the first occurence of the given argument, testing
* for equality using the <tt>equals</tt> method.
*
* @param elem an object.
* @return the index of the first occurrence of the argument in this
* list; returns <tt>-1</tt> if the object is not found.
* @see Object#equals(Object)
* 返回指定位置下标
*/
public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified object in
* this list.
*
* @param elem the desired element.
* @return the index of the last occurrence of the specified object in
* this list; returns -1 if the object is not found.
*/
public int lastIndexOf(Object elem) {
if (elem == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
* 浅拷贝
*
* @return a clone of this <tt>ArrayList</tt> instance.
*/
public Object clone() {
try {
Page<E> v = (Page<E>) super.clone();
v.elementData = (E[])new Object[size];
System.arraycopy(elementData, 0, v.elementData, 0, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* Returns an array containing all of the elements in this list
* in the correct order.
*
* 返回一个一个数组拷贝
*
* @return an array containing all of the elements in this list
* in the correct order.
*
*/
public Object[] toArray() {
Object[] result = new Object[size];
System.arraycopy(elementData, 0, result, 0, size);
return result;
}
/**
* Returns an array containing all of the elements in this list in the
* correct order; the runtime type of the returned array is that of the
* specified array. If the list fits in the specified array, it is
* returned therein. Otherwise, a new array is allocated with the runtime
* type of the specified array and the size of this list.<p>
*
* If the list fits in the specified array with room to spare (i.e., the
* array has more elements than the list), the element in the array
* immediately following the end of the collection is set to
* <tt>null</tt>. This is useful in determining the length of the list
* <i>only</i> if the caller knows that the list does not contain any
* <tt>null</tt> elements.
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list.
* @throws ArrayStoreException if the runtime type of a is not a supertype
* of the runtime type of every element in this list.
* 使用反射动态拷贝数据
* 当a.size<size时执行操作
*/
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), size);
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
*
* @param index index of element to return.
* @return the element at the specified position in this list.
* @throws IndexOutOfBoundsException if index is out of range <tt>(index
* < 0 || index >= size())</tt>.
*/
public E get(int index) {
RangeCheck(index);
return elementData[index];
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of element to replace.
* @param element element to be stored at the specified position.
* @return the element previously at the specified position.
* @throws IndexOutOfBoundsException if index out of range
* <tt>(index < 0 || index >= size())</tt>.
*/
public E set(int index, E element) {
RangeCheck(index);
E oldValue = elementData[index];
elementData[index] = element;
return oldValue;
}
/**
* Appends the specified element to the end of this list.
*
* @param o element to be appended to this list.
* @return <tt>true</tt> (as per the general contract of Collection.add).
*/
public boolean add(E o) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = o;
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted.
* @param element element to be inserted.
* @throws IndexOutOfBoundsException if index is out of range
* <tt>(index < 0 || index > size())</tt>.
*/
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to removed.
* @return the element that was removed from the list.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
* < 0 || index >= size())</tt>.
*/
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
/**
* Removes a single instance of the specified element from this
* list, if it is present (optional operation). More formally,
* removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
* o.equals(e))</tt>, if the list contains one or more such
* elements. Returns <tt>true</tt> if the list contained the
* specified element (or equivalently, if the list changed as a
* result of the call).<p>
*
* @param o element to be removed from this list, if present.
* @return <tt>true</tt> if the list contained the specified element.
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
* 顺序列表之出队
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* Appends all of the elements in the specified Collection to the end of
* this list, in the order that they are returned by the
* specified Collection's Iterator. The behavior of this operation is
* undefined if the specified Collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified Collection is this list, and this
* list is nonempty.)
*
* @param c the elements to be inserted into this list.
* @return <tt>true</tt> if this list changed as a result of the call.
* @throws NullPointerException if the specified collection is null.
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount增容
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* Inserts all of the elements in the specified Collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified Collection's iterator.
*
* @param index index at which to insert first element
* from the specified collection.
* @param c elements to be inserted into this list.
* @return <tt>true</tt> if this list changed as a result of the call.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
* < 0 || index > size())</tt>.
* @throws NullPointerException if the specified Collection is null.
*/
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
/**
* Removes from this List all of the elements whose index is between
* fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
* elements to the left (reduces their index).
* This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
* (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
*
* @param fromIndex index of first element to be removed.
* @param toIndex index after last element to be removed.
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newSize = size - (toIndex-fromIndex);
while (size != newSize)
elementData[--size] = null;
}
/**
* Check if the given index is in range. If not, throw an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
/**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
*
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
int expectedModCount = modCount;
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = (E[])new Object[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
}
该类中的重点方法都已加上注释。
2.创建实体类User
package com.bjsxt.registration.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
private int id;
private String username;
private String password;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.创建DAO操作基类,该类中包含HibernateTemplate注入参数以及常用DAO数据操作方法,当然包含最重要的findByPage方法,代码如下:
package com.bjsxt.registration.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.bjsxt.registration.util.Page;
import com.sun.xml.internal.bind.v2.model.core.ID;
/**
* DAO操作基类<br>
* 本DAO层实现了通用的数据操作
* @author Wing HuiFeng
* @param <T>
* POJO实体对象
* @param <ID>
* ID
*/
@SuppressWarnings("unchecked")
public class BaseDAO<T>{
@Resource
public HibernateTemplate hibernateTemplate;
private static final Logger logger = Logger
.getLogger(BaseDAO.class);
/**
* 保存指定实体类
*
* @param entityobj
* 实体类
*/
public void save(T entity) {
try {
getHibernateTemplate().save(entity);
if (logger.isDebugEnabled()) {
logger.debug("保存实体类成功," + entity.getClass().getName());
}
} catch (RuntimeException e) {
logger.error("保存实体异常," + entity.getClass().getName(), e);
throw e;
}
}
/**
* 删除指定实体
*
* @param entityobj
* 实体类
*/
public void delete(T entity) {
try {
getHibernateTemplate().delete(entity);
if (logger.isDebugEnabled()) {
logger.debug("删除实体类成功," + entity.getClass().getName());
}
} catch (RuntimeException e) {
logger.error("删除实体异常", e);
throw e;
}
}
/**
* 获取所有实体集合
*
* @param entityClass
* 实体
* @return 集合
*/
public List<T> findAll(Class<T> entityClass) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始删除实体:" + entityClass.getName());
}
return getHibernateTemplate().find("from " + entityClass.getName());
} catch (RuntimeException e) {
logger.error("查找指定实体集合异常,实体:" + entityClass.getName(), e);
throw e;
}
}
/**
* 更新或保存指定实体
*
* @param entity
* 实体类
*/
public void saveOrUpdate(T entity) {
try {
getHibernateTemplate().saveOrUpdate(entity);
if (logger.isDebugEnabled()) {
logger.debug("更新或者保存实体成功," + entity.getClass().getName());
}
} catch (RuntimeException e) {
logger.error("更新或保存实体异常", e);
throw e;
}
}
/**
* 查找指定ID实体类对象
*
* @param entityClass
* 实体Class
* @param id
* 实体ID
* @return 实体对象
*/
public T findById(Class<T> entityClass, ID id) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始查找ID为" + id + "的实体:" + entityClass.getName());
}
return (T) getHibernateTemplate().get(entityClass, id);
} catch (RuntimeException e) {
logger.error("查找指定ID实体异常,ID:" + id, e);
throw e;
}
}
/**
* 查询指定HQL,并返回集合
*
* @param hql
* HQL语句
* @param values
* 可变的参数列表
* @return 集合
*/
public List<Object> find(String hql, Object... values) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始查询指定HQL语句," + hql);
}
return getHibernateTemplate().find(hql, values);
} catch (RuntimeException e) {
logger.error("查询指定HQL异常,HQL:" + hql, e);
throw e;
}
}
/**
* 按照HQL语句查询唯一对象.
*
* @param hql
* HQL语句
* @param values
* 可变参数集合
* @return OBJECT对象
*/
public Object findUnique(final String hql, final Object... values) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始查询返回唯一结果的HQL语句," + hql);
}
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query query = createQuery(s, hql, values);
return query.uniqueResult();
}
});
} catch (RuntimeException e) {
logger.error("查询指定HQL异常,HQL:" + hql, e);
throw e;
}
}
/**
* 查找指定HQL并返回INT型
*
* @param hql
* HQL语句
* @param values
* 可变参数列表
* @return INT
*/
public int findInt(final String hql, final Object... values) {
return Integer.parseInt((String) (findUnique(hql, values)));
}
/**
* 获取指定实体Class指定条件的记录总数
*
* @param entityClass
* 实体Class
* @param where
* HQL的查询条件,支持参数列表
* @param values
* 可变参数列表
* @return 记录总数
*/
public int findTotalCount(Class<T> entityClass, final String where,
final Object... values) {
String hql = "select count(e) from " + entityClass.getName() + " as e "
+ where;
return findInt(hql, values);
}
/**
* 获取指定实体Class的记录总数
*
* @param entityClass
* 实体Class
* @return 记录总数
*/
public int findTotalCount(Class<T> entityClass) {
return findTotalCount(entityClass, "");
}
/**
* 查找指定属性的实体集合
*
* @param entityClass
* 实体
* @param propertyName
* 属性名
* @param value
* 条件
* @return 实体集合
*/
public List<T> findByProperty(Class<T> entityClass, String propertyName,
Object value) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始查找指定属性:" + propertyName + "为" + value + "的实体"
+ entityClass.getName());
}
String queryStr = "from " + entityClass.getName()
+ " as model where model." + propertyName + "=?";
return getHibernateTemplate().find(queryStr, value);
} catch (RuntimeException e) {
logger.error("查找指定条件实体集合异常,条件:" + propertyName, e);
throw e;
}
}
/**
* 模糊查询指定条件对象集合 <br>
* 用法:可以实例化一个空的T对象,需要查询某个字段,就set该字段的条件然后调用本方法<br>
* 缺点:目前测试貌似只能支持String的模糊查询,虽然有办法重写,但没必要,其他用HQL<br>
*
* @param entity
* 条件实体
* @return 结合
*/
public List<T> findByExample(T entity) {
try {
List<T> results = getHibernateTemplate().findByExample(entity);
return results;
} catch (RuntimeException re) {
logger.error("查找指定条件实体集合异常", re);
throw re;
}
}
/**
* 补充方法(未测) 据说可以无视session的状态持久化对象
*
* @param entity
* 实体类
* @return 持久后的实体类
*/
public T merge(T entity) {
try {
T result = (T) getHibernateTemplate().merge(entity);
return result;
} catch (RuntimeException re) {
logger.error("merge异常", re);
throw re;
}
}
/**
* 清除实体的锁定状态<br>
* 方法未测
*
* @param entity
* 实体
*/
public void attachClean(T entity) {
try {
getHibernateTemplate().lock(entity, LockMode.NONE);
} catch (RuntimeException re) {
logger.error("实体解锁异常", re);
throw re;
}
}
/**
* 按HQL分页查询.
*
* @param page
* 页面对象
* @param hql
* HQL语句
* @param values
* 可变参数列表
* @return 分页数据
*/
public Page<T> findByPage(final String hql, final Integer offset,final Integer length,
final Object... values) {
try {
if (logger.isDebugEnabled()) {
logger.debug("开始查找指定HQL分页数据," + hql);
}
return (Page<T>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query query = createQuery(s, hql, values);
ScrollableResults sr = query.scroll();
sr.last();
int totalCount = sr.getRowNumber();
query.setFirstResult(length*(offset-1)).setMaxResults(length);
Page p=new Page(query.list());
p.setTotalCount(totalCount+1);
logger.info("查找指定HQL分页数据成功," + hql);
return p;
}
});
} catch (RuntimeException e) {
logger.error("分页查询异常,HQL:" + hql, e);
throw e;
}
}
/**
* 根据查询条件与参数列表创建Query对象
*
* @param session
* Hibernate会话
* @param hql
* HQL语句
* @param objects
* 参数列表
* @return Query对象
*/
public Query createQuery(Session session, String hql, Object... objects) {
Query query = session.createQuery(hql);
if (objects != null) {
for (int i = 0; i < objects.length; i++) {
query.setParameter(i, "%"+objects[i]+"%");
}
}
return query;
}
/**
* 批量删除
*/
public void deleteMany(int[] ids){
Session session=this.hibernateTemplate.getSessionFactory().getCurrentSession();
Transaction tx=session.beginTransaction();
Work work=new Work(){
public void execute(Connection conn) throws SQLException {
//这里可以执行jdbc方法
}
};
//执行work
session.doWork(work);
tx.commit();
session.close();
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public static void main(String[] args) {
String sql="from User u where u.username=?";
int s=sql.indexOf("where");
sql=sql.substring(0,s);
System.out.println(sql);
}
}
4.创建UserDAO
package com.bjsxt.registration.dao.user;
import java.util.List;
import com.bjsxt.registration.model.User;
import com.bjsxt.registration.util.Page;
public interface UserDAO {
public void save(User u);
public boolean checkUserExistsWithName(String username);
public List<User> getUsers();
public User loadById(int id);
//专为分页提供的方法
public Page<User> findCurrentPage(Integer offset, Integer length,String...values);
}
5.创建UserDAOImpl
/**
* 根据用户名模糊分页查询
*/
public Page<User> findCurrentPage(Integer offset, Integer length,String...values){
return this.findByPage(findByPage,offset,length,values);
}
6.创建底层Action,BaseAction,包含log4j,session创建及ActionSupport的支持,省去了在子类中创建了。
package com.bjsxt.registration.action;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import com.bjsxt.registration.util.Page;
import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.ActionSupport;
public abstract class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware {
/**
*
*/
private static final long serialVersionUID = 6230751116897773145L;
public static final Log log = LogFactory.getLog(BaseAction.class);
protected Map<String, Object> session;
protected HttpServletRequest request;
//分页相关参数
protected int pageNum =1;
protected int numPerPage = 5;
protected int totalCount;
protected int currentPage;
protected int totalPage;
//存放分页数据
protected Page page;
/**
* 装载当前页数据。
* @param hql 查询语句
* @return Page
*/
protected <T> Page<T> createPage(Page page){
page.setNumPerPage(getNumPerPage());
page.setPageNum(getPageNum());
page.setTotalPage(gainTotalPage(page.getTotalCount(),getNumPerPage()));
setPage(page);
return page;
}
public int gainTotalPage(int totalCount, int rowsperpage) {
int pages = 0;
if (totalCount == 0){
pages = 0;
}else {
if (totalCount <= rowsperpage)
pages = 1;
if (totalCount > rowsperpage && totalCount % rowsperpage == 0)
pages = totalCount / rowsperpage;
if (totalCount > rowsperpage && totalCount % rowsperpage != 0)
pages = totalCount / rowsperpage + 1;
}
return pages;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getNumPerPage() {
return numPerPage;
}
public void setNumPerPage(int numPerPage) {
this.numPerPage = numPerPage;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public Map<String, Object> getSession() {
return session;
}
}
7.创建Action在子类中只要继承BaseAction类就行了
package com.bjsxt.registration.action.user;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.bjsxt.registration.action.BaseAction;
import com.bjsxt.registration.model.User;
import com.bjsxt.registration.service.user.UserManager;
import com.bjsxt.registration.vo.UserRegisterInfo;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Component("u")
@Scope("prototype")
public class UserAction extends BaseAction {
private static final long serialVersionUID = 1L;
private UserRegisterInfo info = new UserRegisterInfo();
private UserManager userManager;
private List<User> users;
private User user;
//查询条件
private String where="";
public UserAction(){
System.out.println("user action created!");
}
public UserRegisterInfo getInfo() {
return info;
}
public void setInfo(UserRegisterInfo info) {
this.info = info;
}
/**
* 测试分页
* 更改参数很简单直接在覆盖父类参数即可
*/
public String userlist(){
page=userManager.findCurrentPage(this.pageNum,
this.numPerPage, where);
createPage(page);
if(page.getPageNum()>page.getTotalPage())
return "redirect";
return "userlist";
}
/**
* 测试分页
* 更改参数很简单直接在覆盖父类参数即可
*/
public String getlist(){
//设定每页记录数,如果不设置则为5
super.numPerPage = 2;
page=userManager.findCurrentPage(this.pageNum,
this.numPerPage, where);
createPage(page);
if(page.getPageNum()>page.getTotalPage())
return "redirect";
return "getlist";
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
//http://127.0.0.1:8080/combine/u!load.action?id=1
public String load() {
//Sturts2中不需要创建Request对象向jsp输出数据
user = this.userManager.loadById(info.getId());
return "load";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserManager getUserManager() {
return userManager;
}
@Resource
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
8.配置Struts2参数
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="registration" extends="struts-default">
<action name="u" class="u">
<result name="success">/registerSuccess.jsp</result>
<result name="userlist">/userlist.jsp</result>
<result name="getlist">/getlist.jsp</result>
<result name="redirect" type="redirect">u!getlist.action</result>
</action>
</package>
</struts>
9.前台post方法jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<SCRIPT type="text/javascript" src="<%=basePath%>js/jquery-1.4.4.js"></SCRIPT>
<SCRIPT type="text/javascript" src="<%=basePath%>js/common.js"></SCRIPT>
<SCRIPT type="text/javascript">
</SCRIPT>
</head>
<body>
<h1>用户列表</h1>
<form id="pagerForm" name="pagerForm"
action="u!userlist.action" method="get">
<input type="hidden" name="pageNum" id="pageNum" value="1" />
<input type="hidden" name="parentName" id="parentName"
value="<s:property value='parentName'/>" />
<input type="hidden" name="where" value="${where }">
<input type="hidden" name="numPerPage" id="numPerPage"
value="<s:property value='page.numPerPage'/>" />
<!-- 可选,每页显示多少行 -->
</form>
<div style="height:30px;">
<form action="u!userlist.action" method="post">
<div class="" style="float:left; margin-right:20px;">
<input type="hidden" name="pageNum" id="pageNum" value="1" />
名称:<input name="where" id="where" type="text" class="sr2" value="${where }" />
<input name="_search" id="_search" type="submit" value="查询" />
</div>
</form>
</div>
<div>
<form>
<table width="600" border="1" cellspacing="2" cellpadding="3">
<tr>
<td>主键</td>
<td>用户名</td>
<td>密码</td>
<td>操作</td>
</tr>
<s:iterator value="page" var="p" status="s">
<tr>
<td>
<s:property value="#p.id"/>
</td>
<td>
<s:if test="#p.username != ''">${p.username}</s:if>
<s:else >未知</s:else>
</td>
<td>
<s:if test="#p.password != ''">${p.password}</s:if>
<s:else >未知</s:else>
</td>
<td>CRUD</td>
</tr>
</s:iterator>
</table>
</form>
</div>
<table>
<tr bgcolor="#ffffff">
<td height="30" colspan="7" style="line-height: 30px;">
<div class="imag">
<s:if test="page.pageNum !=1">
<a href="javascript:pagerFormFirst();"><img
src="images/jt-04.jpg" width="30" height="30" title="首页" border="0" style="vertical-align:middle"/></a>
<a href="javascript:pagerFormBack(<s:property value='page.pageNum'/>);"><img
src="images/jt-02.jpg" title="上一页" style="vertical-align:middle"/></a>
</s:if>
<s:else>
<img src="images/jt-04.jpg" width="30" height="30" title="首页" border="0" style="vertical-align:middle" />
<img src="images/jt-02.jpg" title="上一页" style="vertical-align:middle"/>
</s:else>
<s:if test="page.pageNum != page.totalPage && page.totalPage != 0">
<a href="javascript:pagerFormForward(<s:property value='page.pageNum'/>);"><img
src="images/jt-01.jpg" title="下一页" border="0" style="vertical-align:middle"/></a>
<a href="javascript:pagerFormLast(<s:property value='page.totalPage'/>);"><img
src="images/jt-03.jpg" title="尾页" border="0" style="vertical-align:middle"/></a>
</s:if>
<s:else>
<img src="images/jt-01.jpg" title="下一页" border="0" style="vertical-align:middle"/>
<img src="images/jt-03.jpg" title="尾页" border="0" style="vertical-align:middle"/>
</s:else>
现在是第
<span class="STYLE3"><s:property value="page.pageNum" />
</span>页,一共有
<span class="STYLE4"><s:property value="page.totalPage" />
</span>页 共有
<s:property value="page.totalCount" />
条信息
</div>
<div>
页面大小
<select name="perNum" id="perNum" class="sec1"
οnchange="pageSumSet();">
<option value="10">
10
</option>
<s:if test="page.numPerPage == 30">
<option value="30" selected="selected">
30
</option>
<option value="50">
50
</option>
</s:if>
<s:else>
<option value="30">
30
</option>
<s:if test="page.numPerPage == 50">
<option value="50" selected="selected">
50
</option>
</s:if>
<s:else>
<option value="50">
50
</option>
</s:else>
</s:else>
</select>
转到
<input type="text" id="selectPage" name="selectPage" style="width:30px;" />
<a href="###"
οnclick="pagerFormSelect(<s:property value='page.totalPage'/>);"><img
src="images/go.jpg" style="vertical-align:middle"/></a>
</div>
</td>
</tr>
</table>
<s:debug></s:debug>
</body>
</html>
10.创建common.js
/**
* 分页的下一页请求
* @param pageNum
* @return
*/
function pagerFormForward(pageNum){
$("#pageNum").val(pageNum+1);
$("#pagerForm").submit();
}
/**
* 分页的上一页请求
* @param pageNum
* @return
*/
function pagerFormBack(pageNum){
$("#pageNum").val(pageNum-1);
$("#pagerForm").submit();
}
/**
* 分页的首页请求
* @return
*/
function pagerFormFirst(){
$("#pageNum").val(1);
$("#pagerForm").submit();
}
/**
* 分页的尾页请求
* @param totalPage
* @return
*/
function pagerFormLast(totalPage){
$("#pageNum").val(totalPage);
$("#pagerForm").submit();
}
/**
* 根据输入的页数跳转
* @param totalPage
* @return
*/
function pagerFormSelect(totalPage){
var page = $("#selectPage").val();
var re=/^[0-9]$/;
if(page.search(re)=='-1'){
alert("请输入数字!");
}else if(page > totalPage || page <= 0){
alert("输入的页数不存在!");
}else{
$("#pageNum").val(page);
$("#pagerForm").submit();
}
}
/**
* 选择每页显示数量
* @param numPerPage
* @return
*/
function pageSumSet(){
var perSum = $("#perNum").val();
$("#numPerPage").val(perSum);
$("#pagerForm").submit();
}
/**
* table鼠标点击划过样式
* @return
*/
function tableCss(){
//奇偶行变色
$("tr:odd").attr("bgcolor", "#FFFFFF");
$("tr:even").attr("bgcolor", "#e6f4f9");
//var cl = "";
//鼠标游过变色
//$("#listTable tr").hover(function(){
// cl = $(this).has("td").attr("class");
// $(this).has("td").attr("class", "hover");
//},function(){
// $(this).has("td").attr("class", cl);
//});
//选中加边框
//$("#listTable tr").click(function(){
//$("#listTable tr").css("background-color","");
//$(this).has("td").css("background-color","#8E8E8E");
//});
}
10.创建get方式jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<SCRIPT type="text/javascript" src="<%=basePath%>js/jquery-1.4.4.js"></SCRIPT>
<SCRIPT type="text/javascript" src="<%=basePath%>js/common.js"></SCRIPT>
<SCRIPT type="text/javascript">
</SCRIPT>
</head>
<body>
<h1>用户列表</h1>
<form id="pagerForm" name="pagerForm"
action="u!getlist.action" method="get">
<input type="hidden" name="pageNum" id="pageNum" value="1" />
<input type="hidden" name="numPerPage" id="numPerPage"
value="<s:property value='page.numPerPage'/>" />
<input type="hidden" name="where" value="${where }">
<!-- 可选,每页显示多少行 -->
</form>
<div style="height:30px;">
<form action="u!getlist.action" method="get">
<div class="" style="float:left; margin-right:20px;">
<input type="hidden" name="pageNum" id="pageNum" value="1" />
名称:<input name="where" id="where" type="text" class="sr2" value="${where }" />
<input type="hidden" name="numPerPage" id="numPerPage"
value="<s:property value='page.numPerPage'/>" />
<input name="" id="_search" type="submit" value="查询" />
</div>
</form>
</div>
<div>
<form>
<table width="600" border="1" cellspacing="2" cellpadding="3">
<tr>
<td>主键</td>
<td>用户名</td>
<td>密码</td>
<td>操作</td>
</tr>
<s:iterator value="page" var="p" status="s">
<tr>
<td>
<s:property value="#p.id"/>
</td>
<td>
<s:if test="#p.username != ''">${p.username}</s:if>
<s:else >未知</s:else>
</td>
<td>
<s:if test="#p.password != ''">${p.password}</s:if>
<s:else >未知</s:else>
</td>
<td>CRUD</td>
</tr>
</s:iterator>
</table>
</form>
</div>
<table>
<tr bgcolor="#ffffff">
<td height="30" colspan="7" style="line-height: 30px;">
<div class="imag">
<s:if test="page.pageNum !=1">
<a href="u!getlist.action?pageNum=1&numPerPage=<s:property value='page.numPerPage'/>&where=${where }"><img
src="images/jt-04.jpg" width="30" height="30" title="首页" border="0" style="vertical-align:middle"/></a>
<a href="u!getlist.action?pageNum=<s:property value='page.pageNum-1'/>&numPerPage=<s:property value='page.numPerPage'/>&where=${where }"><img
src="images/jt-02.jpg" title="上一页" style="vertical-align:middle"/></a>
</s:if>
<s:else>
<img src="images/jt-04.jpg" width="30" height="30" title="首页" border="0" style="vertical-align:middle" />
<img src="images/jt-02.jpg" title="上一页" style="vertical-align:middle"/>
</s:else>
<s:if test="page.pageNum != page.totalPage && page.totalPage != 0">
<a href="u!getlist.action?pageNum=<s:property value='page.pageNum+1'/>&numPerPage=<s:property value='page.numPerPage'/>&where=${where }"><img
src="images/jt-01.jpg" title="下一页" border="0" style="vertical-align:middle"/></a>
<a href="u!getlist.action?pageNum=<s:property value='page.totalPage'/>&numPerPage=<s:property value='page.numPerPage'/>&where=${where }"><img
src="images/jt-03.jpg" title="尾页" border="0" style="vertical-align:middle"/></a>
</s:if>
<s:else>
<img src="images/jt-01.jpg" title="下一页" border="0" style="vertical-align:middle"/>
<img src="images/jt-03.jpg" title="尾页" border="0" style="vertical-align:middle"/>
</s:else>
现在是第
<span class="STYLE3"><s:property value="page.pageNum" />
</span>页,一共有
<span class="STYLE4"><s:property value="page.totalPage" />
</span>页 共有
<s:property value="page.totalCount" />
条信息
</div>
<div>
页面大小
<select name="perNum" id="perNum" class="sec1"
οnchange="pageSumSet();">
<option value="10">
10
</option>
<s:if test="page.numPerPage == 30">
<option value="30" selected="selected">
30
</option>
<option value="50">
50
</option>
</s:if>
<s:else>
<option value="30">
30
</option>
<s:if test="page.numPerPage == 50">
<option value="50" selected="selected">
50
</option>
</s:if>
<s:else>
<option value="50">
50
</option>
</s:else>
</s:else>
</select>
转到
<input type="text" id="selectPage" name="selectPage" style="width:30px;" />
<a href="###"
οnclick="pagerFormSelect(<s:property value='page.totalPage'/>);"><img
src="images/go.jpg" style="vertical-align:middle"/></a>
</div>
</td>
</tr>
</table>
<s:debug></s:debug>
</body>
</html>
Ok.全部文件操作完成,下面打开tomcat进行测试。测试地址
http://127.0.0.1:8080/pager/u!userlist.action
http://127.0.0.1:8080/pager/u!getlist.action
效果展示:
Get方式与Post方式结果是相同是只是页面地址会携带参数。
下面补充一下sql语句:
/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.5.27 : Database - spring
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `t_log` */
DROP TABLE IF EXISTS `t_log`;
CREATE TABLE `t_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`msg` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `t_log` */
insert into `t_log`(`id`,`msg`) values (1,'a user saved!'),(2,'a user saved!'),(3,'a user saved!'),(4,'a user saved!'),(5,'a user saved!');
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`(`id`,`password`,`username`) values (1,'admin','admin'),(5,'11','测试乱码11'),(6,'dasda','dasdas'),(7,'111','111'),(8,'111','你好世界'),(9,'111','你好世界?'),(10,'11','fafds'),(11,'222','222'),(12,'proxool','proxool'),(13,NULL,NULL),(14,'shit','shit'),(16,'adcChina','adcChina'),(17,'icbc.com','icbc.com'),(18,'register','register'),(19,'1111','register11'),(20,'register22','register22'),(21,'register33','register33'),(22,'用户名','用户名'),(23,'e421083458','e421083458'),(45,NULL,'111'),(46,NULL,'dsad'),(47,NULL,'444'),(48,NULL,'444'),(49,NULL,'444');
/*Table structure for table `users` */
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `users` */
insert into `users`(`id`,`password`,`username`) values (1,'lisi','lisi'),(2,'lisi','lisi'),(3,'lisi','lisi'),(4,'lisi','lisi'),(5,'lisi','lisi');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;