Action层
package com.action;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dao.hib.BbsSection;
import com.dao.hib.BbsSectionDAO;
import com.dao.hib.BbsTopic;
import com.dao.hib.BbsTopicDAO;
import com.dao.hib.BbsUsers;
import com.dao.hib.BbsUsersDAO;
import com.dao.hib.Pager;
import com.entity.BBSTopic;
/**
* 帖子控制器
* @author Administrator
*
*/
public class BBSTopicAction extends BaseAction {
BbsTopicDAO tDAO = new BbsTopicDAO();
private BbsTopic topic;
private int uid;
private int sid;
/**接受Map参数*/
private Map<String,String[]> hp ;
/**页码*/
private int pageCode;
//---模糊查询参数----
private String ttopic;
private String ttcontents;
private String keywordName;
private String keywordValue;
/**
* 发布帖子
* @return
*/
public String pub(){
BbsUsers user = new BbsUsersDAO().findById(uid);
BbsSection sec = new BbsSectionDAO().findById(sid);
topic.setBbsUsers(user);
topic.setBbsSection(sec);
topic.setTtime(new Timestamp(System.currentTimeMillis()));
BbsTopicDAO tDAO = new BbsTopicDAO();
tDAO.save(topic);
return SUCCESS;
}
/**
* 获取所有帖子列表
* @return
*/
public String getAll(){
List<BBSTopic> all = tDAO.findAll();
//将数据放入request
request.setAttribute("allTopic", all);
return "topicAll";
}
/**
* 分页查询帖子数据
* @return
*/
public String list(){
//8.放入request或Session
sessoin.setAttribute("topicPager", tDAO.findByPage(pageCode, keywordName, keywordValue, sessoin));
//跳转视图
return "list";
}
public BbsTopic getTopic() {
return topic;
}
public void setTopic(BbsTopic topic) {
this.topic = topic;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public Map<String, String[]> getHp() {
return hp;
}
public void setHp(Map<String, String[]> hp) {
this.hp = hp;
}
public int getPageCode() {
return pageCode;
}
public void setPageCode(int pageCode) {
this.pageCode = pageCode;
}
public String getTtopic() {
return ttopic;
}
public void setTtopic(String ttopic) {
this.ttopic = ttopic;
}
public String getTtcontents() {
return ttcontents;
}
public void setTtcontents(String ttcontents) {
this.ttcontents = ttcontents;
}
public String getKeywordName() {
return keywordName;
}
public void setKeywordName(String keywordName) {
this.keywordName = keywordName;
}
public String getKeywordValue() {
return keywordValue;
}
public void setKeywordValue(String keywordValue) {
this.keywordValue = keywordValue;
}
}
DAO层
package com.dao.hib;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A data access object (DAO) providing persistence and search support for
* BbsTopic 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.dao.hib.BbsTopic
* @author MyEclipse Persistence Tools
*/
public class BbsTopicDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory
.getLogger(BbsTopicDAO.class);
// property constants
public static final String TREPLY_COUNT = "treplyCount";
public static final String TFACE = "tface";
public static final String TTOPIC = "ttopic";
public static final String TCONTENTS = "tcontents";
public static final String TCLICK_COUNT = "tclickCount";
public static final String TSTATE = "tstate";
public void save(BbsTopic transientInstance) {
log.debug("saving BbsTopic instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(BbsTopic persistentInstance) {
log.debug("deleting BbsTopic instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public BbsTopic findById(java.lang.Integer id) {
log.debug("getting BbsTopic instance with id: " + id);
try {
BbsTopic instance = (BbsTopic) getSession().get(
"com.dao.hib.BbsTopic", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(BbsTopic instance) {
log.debug("finding BbsTopic instance by example");
try {
List results = getSession().createCriteria("com.dao.hib.BbsTopic")
.add(Example.create(instance)).list();
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 BbsTopic instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from BbsTopic as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByTreplyCount(Object treplyCount) {
return findByProperty(TREPLY_COUNT, treplyCount);
}
public List findByTface(Object tface) {
return findByProperty(TFACE, tface);
}
public List findByTtopic(Object ttopic) {
return findByProperty(TTOPIC, ttopic);
}
public List findByTcontents(Object tcontents) {
return findByProperty(TCONTENTS, tcontents);
}
public List findByTclickCount(Object tclickCount) {
return findByProperty(TCLICK_COUNT, tclickCount);
}
public List findByTstate(Object tstate) {
return findByProperty(TSTATE, tstate);
}
/**
* 分页查询
* @param pageCode
* @param keywordName
* @param keywordValue
* @param session
* @return
*/
public Pager findByPage(int pageCode,String keywordName,String keywordValue,HttpSession session){
StringBuffer hql = new StringBuffer();
Map map = new HashMap();
hql.append("select count(tid) from BbsTopic where 1=1 ");
//取出原来的
if (keywordName!=null&&keywordValue!=null)
{
map.put(keywordName, "%" + keywordValue.trim() + "%"); //like
hql.append("and "+keywordName+" like :"+keywordName); //命名查询
}else if(session.getAttribute("topicPager")!=null){
hql = new StringBuffer(((Pager)session.getAttribute("topicPager")).getHql());
map = ((Pager)session.getAttribute("topicPager")).getMap();
}
String queryHql = hql.substring(hql.indexOf("from"));
int rowCount = getTotalCount(hql.toString(), map);
Pager pager = new Pager(rowCount,pageCode);
List result = findPageByQuery(pager.getPageNumber(), pager.getLimit(),
queryHql, map);
pager.setList(result);
pager.setHql(hql.toString());
pager.setMap(map);
return pager;
}
/**
* @function 分页显示符合所有的记录数,将查询结果封装为Pager
* @param pageNo
* 当前页数
* @param pageSize
* 每页显示的条数
* @param instance
* 将查询条件封装为专家Bean
* @return 查询结果Pager
*/
public List<Object> findPageByQuery(int pageNo, int pageSize, String hql,
Map map) {
List<Object> result = null;
try {
Query query = getSession().createQuery(hql);
//通过遍历参数Map,给指定查询设置命名参数及值
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
query.setParameter(key.toString(), map.get(key));
}
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
result = query.list();
} catch (RuntimeException re) {
throw re;
}
return result;
}
/**
* @function 根据查询条件查询记录数的个数
* @param hql
* hql查询语句
* @param map
* 用map封装查询条件
* @return 数据库中满足查询条件的数据的条数
*/
public int getTotalCount(String countHql, Map map) {
try {
Query query = this.getSession().createQuery(countHql);
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
query.setParameter(key.toString(), map.get(key));
}
Integer i = ((Long) query.list().get(0)).intValue();
return i;
} catch (RuntimeException re) {
throw re;
}
}
public List findAll() {
log.debug("finding all BbsTopic instances");
try {
String queryString = "from BbsTopic";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public BbsTopic merge(BbsTopic detachedInstance) {
log.debug("merging BbsTopic instance");
try {
BbsTopic result = (BbsTopic) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(BbsTopic instance) {
log.debug("attaching dirty BbsTopic instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(BbsTopic instance) {
log.debug("attaching clean BbsTopic instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
分页工具
package com.dao.hib;
import java.util.List;
import java.util.Map;
/**
* 用于分页的工具类
*
* @author 取网名
*/
public class Pager<T> {
//Pager<User> pager = new Pager<User>();
private List<T> list; // 对象记录结果集
private int total = 0; // 总记录数
private int limit = 4; // 每页显示记录数
private int pages = 1; // 总页数
private int pageNumber = 1; // 当前页
private boolean isFirstPage = false; // 是否为第一页
private boolean isLastPage = false; // 是否为最后一页
private boolean hasPreviousPage = false; // 是否有前一页
private boolean hasNextPage = false; // 是否有下一页
private int navigatePages = 8; // 导航页码数
private int[] navigatePageNumbers; // 所有导航页号
//Hibernate
/**存储参数名及值*/
private Map map;
/**存储HQL(计数)*/
private String hql;
/**
*
* @param total 总记录数
* @param pageNumber 当前页码
*/
public Pager(int total, int pageNumber) {
init(total, pageNumber, limit);
}
public Pager(int total, int pageNumber, int limit) {
init(total, pageNumber, limit);
}
private void init(int total, int pageNumber, int limit) {
// 设置基本参数
this.total = total;
this.limit = limit;
this.pages = (this.total - 1) / this.limit + 1;
// 根据输入可能错误的当前号码进行自动纠正
if (pageNumber < 1) {
this.pageNumber = 1;
} else if (pageNumber > this.pages) {
this.pageNumber = this.pages;
} else {
this.pageNumber = pageNumber;
}
// 基本参数设定之后进行导航页面的计算
calcNavigatePageNumbers();
// 以及页面边界的判定
judgePageBoudary();
}
/**
* 计算导航页
*/
private void calcNavigatePageNumbers() {
// 当总页数小于或等于导航页码数时
if (pages <= navigatePages) {
navigatePageNumbers = new int[pages];
for (int i = 0; i < pages; i++) {
navigatePageNumbers[i] = i + 1;
}
} else { // 当总页数大于导航页码数时
navigatePageNumbers = new int[navigatePages];
int startNum = pageNumber - navigatePages / 2;
int endNum = pageNumber + navigatePages / 2;
if (startNum < 1) {
startNum = 1;
// (最前navigatePages页
for (int i = 0; i < navigatePages; i++) {
navigatePageNumbers[i] = startNum++;
}
} else if (endNum > pages) {
endNum = pages;
// 最后navigatePages页
for (int i = navigatePages - 1; i >= 0; i--) {
navigatePageNumbers[i] = endNum--;
}
} else {
// 所有中间页
for (int i = 0; i < navigatePages; i++) {
navigatePageNumbers[i] = startNum++;
}
}
}
}
/**
* 判定页面边界
*/
private void judgePageBoudary() {
isFirstPage = pageNumber == 1;
isLastPage = pageNumber == pages && pageNumber != 1;
hasPreviousPage = pageNumber > 1;
hasNextPage = pageNumber < pages;
}
public void setList(List<T> list) {
this.list = list;
}
/**
* 得到当前页的内容
*
* @return {List}
*/
public List<T> getList() {
return list;
}
/**
* 得到记录总数
*
* @return {int}
*/
public int getTotal() {
return total;
}
/**
* 得到每页显示多少条记录
*
* @return {int}
*/
public int getLimit() {
return limit;
}
/**
* 得到页面总数
*
* @return {int}
*/
public int getPages() {
return pages;
}
/**
* 得到当前页号
*
* @return {int}
*/
public int getPageNumber() {
return pageNumber;
}
/**
* 得到所有导航页号
*
* @return {int[]}
*/
public int[] getNavigatePageNumbers() {
return navigatePageNumbers;
}
public boolean isFirstPage() {
return isFirstPage;
}
public boolean isLastPage() {
return isLastPage;
}
public boolean hasPreviousPage() {
return hasPreviousPage;
}
public boolean hasNextPage() {
return hasNextPage;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[").append("total=").append(total).append(",pages=").append(
pages).append(",pageNumber=").append(pageNumber).append(
",limit=").append(limit).append(",isFirstPage=").append(
isFirstPage).append(",isLastPage=").append(isLastPage).append(
",hasPreviousPage=").append(hasPreviousPage).append(
",hasNextPage=").append(hasNextPage).append(
",navigatePageNumbers=");
int len = navigatePageNumbers.length;
if (len > 0)
sb.append(navigatePageNumbers[0]);
for (int i = 1; i < len; i++) {
sb.append(" " + navigatePageNumbers[i]);
}
sb.append(",list.size=" + list.size());
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
// int totalCount=Integer.valueOf(queryCount.uniqueResult().toString());
// Pager pager=new Pager(totalCount, pageNumber,limit);
// queryList.setFirstResult((pager.getPageNumber()-1)*limit); //容错处理
// queryList.setMaxResults(limit);
// pager.setList(queryList.list());
// return pager;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public String getHql() {
return hql;
}
public void setHql(String hql) {
this.hql = hql;
}
}