项目需要用到Ajax,最开始本想用Jquery,最后权衡下选择了DWR。
这里说的是DWR整合SSH,其实DWR完全没有必要和Struts2结合,毕竟DWR需要返回的是Object,而Struts2直接转向了页面。非要强制将二者整合,只能做一个伪Action,这个伪Action返回的还是Object。当然DWR和Spring、Hibernate结合就非常好,可以将Struts2戏称为小三了 O(∩_∩)O ~
扯得有点远了,步入正题。
需求描述:
根据新闻标题(title)利用Ajax模糊查询新闻集合(这里将这些新闻集合称之为相关新闻),并将得到的相关新闻在页面以列表的形式展示出来,且需要实现分页。
框架搭建(这里只讲与DWR有关的配置,DWR--Version: 2.0.1)à
web.xml:
dwr配置文件:
dwr的spring配置文件(这里将其单独作为一个配置文件,需将其import到applicationContext.xml内,这里将伪action交于spring代管):
新闻Bean(只列举出页面列表迭代用到的字段):
dwr package:
由于service只是简单的dao的引用,所以这里只列出核心的两个类: DWRQueryDaoImpl 和DWRQuery (DWRQuery--这个伪Action的小三)
DWRQueryDaoImpl:
public List<News> getNewsListByTitle(String title,String colid){
try {
String hql="from News as o where o.title like '%"+title.trim()+"%' and o.pubstate='已发布' and o.newscolumn.id='"+colid.trim() +"' order by pubstate desc";
return (List<News>)super.getHibernateTemplate().find(hql);
} catch (RuntimeException re) {
throw re;
}
}
public List<News> getNewsListByPage(final String title,final String colid,final int pageNo,final int pagesize){
final Map<String,List<News>> map=new HashMap<String,List<News>>();
try {
super.getHibernateTemplate().execute(new HibernateCallback<List<News>>()
{
public List<News> doInHibernate(Session session) throws HibernateException, SQLException
{
String hql="from News as o where o.title like '%"+title.trim()+"%' and o.pubstate='已发布' and o.newscolumn.id='"+colid.trim() +"' order by pubstate desc";
Query query = session.createQuery(hql);
int firstindex=(pageNo-1)*pagesize;
query.setFirstResult(firstindex).setMaxResults(pagesize);
List list= query.list();
map.put("map",list);
return null;
}
});
List returnList=map.get("map");
return returnList;
} catch (RuntimeException re) {
throw re;
}
}
DWRQuery :
public Map dwrQuery(String title,String colid,int pageNo){
List<News> list=new ArrayList<News>();
list=qes.getNewsListByTitle(title, colid);
//获得总记录数
Integer recordCount=list.size();
//总页数
int pageCount=(int)Math.ceil(recordCount.doubleValue()/this.getPagesize());
list.clear();
list=qes.getNewsListByPage(title, colid, pageNo, this.getPagesize());
Map map=new HashMap();
map.put("recordCount", recordCount);//总记录数
map.put("pageSize", this.getPagesize());//每页显示数
map.put("pageCount", pageCount);//总页数
map.put("dataList", list);//新闻集合
return map;
}
页面:
//最终实现的分页效果
当前页:第 1 页 |总记录数: 21条 |每页显示: 10条 |总页数: 3页 |首页上一页下一页末页
DWR整合SSH大致总结到这里,粘了比较多的代码。希望能给有类似需求的朋友们提供一点点帮助。