项目需要用到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:
[xhtml]
view plain
copy
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>dwr-invoker</servlet-name>
- <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
- <init-param>
- <param-name>debug</param-name>
- <param-value>true</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>dwr-invoker</servlet-name>
- <url-pattern>/dwr/*</url-pattern>
- </servlet-mapping>
dwr配置文件:
[xhtml]
view plain
copy
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEdwrPUBLIC"-//GetAheadLimited//DTDDirectWebRemoting
- 2.0//EN""http://www.getahead.ltd.uk/dwr/dwr20.dtd">
- <dwr>
- <allow>
- <createjavascript="showList"creator="spring"
- scope="application">
- <paramname="beanName"value="dwrquery"/>
- </create>
- <convertmatch="org.huajun.news.bean.News"converter="bean">
- </convert>
- <convertconverter="bean"match="java.lang.StackTraceElement"/>
- <convertconverter="exception"match="java.lang.Exception"/>
- </allow>
- </dwr>
dwr的spring配置文件(这里将其单独作为一个配置文件,需将其import到applicationContext.xml内,这里将伪action交于spring代管):
[xhtml]
view plain
copy
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- default-autowire="byName"
- xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
- <beanid="dwrquery"class="org.huajun.dwr.action.DWRQuery"scope="prototype">
- <propertyname="qes">
- <refbean="qes"/>
- </property>
- </bean>
- <beanid="qes"class="org.huajun.dwr.serviceImpl.DWRQueryServiceImpl"scope="prototype">
- <propertyname="qd">
- <refbean="qd"/>
- </property>
- </bean>
- <beanid="qd"class="org.huajun.dwr.daoImpl.DWRQueryDaoImpl"></bean>
- </beans>
新闻Bean(只列举出页面列表迭代用到的字段):
[java]
view plain
copy
- privateStringtitle;//标题
- privateStringcreater;//录入人
- privateintchecks;//点击数
dwr package:
由于service只是简单的dao的引用,所以这里只列出核心的两个类: DWRQueryDaoImpl 和DWRQuery (DWRQuery--这个伪Action的小三)
DWRQueryDaoImpl:
[java]
view plain
copy
- publicList<News>getNewsListByTitle(Stringtitle,Stringcolid){
- try{
- Stringhql="fromNewsasowhereo.titlelike'%"+title.trim()+"%'ando.pubstate='已发布'ando.newscolumn.id='"+colid.trim()+"'orderbypubstatedesc";
- return(List<News>)super.getHibernateTemplate().find(hql);
- }catch(RuntimeExceptionre){
- throwre;
- }
- }
- publicList<News>getNewsListByPage(finalStringtitle,finalStringcolid,finalintpageNo,finalintpagesize){
- finalMap<String,List<News>>map=newHashMap<String,List<News>>();
- try{
- super.getHibernateTemplate().execute(newHibernateCallback<List<News>>()
- {
- publicList<News>doInHibernate(Sessionsession)throwsHibernateException,sqlException
- {
- Stringhql="fromNewsasowhereo.titlelike'%"+title.trim()+"%'ando.pubstate='已发布'ando.newscolumn.id='"+colid.trim()+"'orderbypubstatedesc";
- Queryquery=session.createQuery(hql);
- intfirstindex=(pageNo-1)*pagesize;
- query.setFirstResult(firstindex).setMaxResults(pagesize);
- Listlist=query.list();
- map.put("map",list);
- returnnull;
- }
- });
- ListreturnList=map.get("map");
- returnreturnList;
- }catch(RuntimeExceptionre){
- throwre;
- }
- }
DWRQuery :
[java]
view plain
copy
- publicMapdwrQuery(Stringtitle,Stringcolid,intpageNo){
- List<News>list=newArrayList<News>();
- list=qes.getNewsListByTitle(title,colid);
- //获得总记录数
- IntegerrecordCount=list.size();
- //总页数
- intpageCount=(int)Math.ceil(recordCount.doubleValue()/this.getPagesize());
- list.clear();
- list=qes.getNewsListByPage(title,colid,pageNo,this.getPagesize());
- Mapmap=newHashMap();
- map.put("recordCount",recordCount);//总记录数
- map.put("pageSize",this.getPagesize());//每页显示数
- map.put("pageCount",pageCount);//总页数
- map.put("dataList",list);//新闻集合
- returnmap;
- }
页面:
[xhtml] view plaincopy
- <!--DWRJS-->
- <scripttype="text/javascript">
- currentPage=1;//当前页码全局变量
- functionchangtable(pageNo){
- if(pageNo<1){
- pageNo=1;//当前页为1
- }
- currentPage=pageNo;//根据当前页数修改全局变量
- varquerytitle=document.getElementById("querytitle");//这里是查询字段
- //这里调用DWRQuery的dwrQuery方法
- showList.dwrQuery(querytitle.value,callBackMethod);
- }
- functioncallBackMethod(map){
- varshowmsg=document.getElementById("showmsg");
- varcolname=document.getElementById("colname").value;
- showmsg.innerHTML="";
- DWRUtil.removeAllRows("tablebody");
- //没有查询到相应记录
- if(map['dataList'].length==0){
- showmsg.innerHTML="<fontcolor='red'>没有查询到相应记录!</font>";
- }else{
- //这里调用的DWRUtil.addRows方法可以参考我的上一篇文章
- DWRUtil.addRows("tablebody",map['dataList'],
- [
- function(item){
- return" <inputtype='checkBox'name='checkBox'value='"+item.id+"'/>"
- },
- function(item){
- return" <atarget='_blank'href="pubnews!looknew.action?id="+item.id+"'>"+item.title+"</a>"
- },
- function(item){return" "+item.creater},
- function(item){return" "+item.checks}
- ],
- {escapeHtml:false});
- }
- showPageBar(map,currentPage);//根据全局当前页数调用显示页面导航的函数
- }
- //显示页码导航
- functionshowPageBar(map,pageNo){
- varpageBar=document.getElementById("pageDiv");
- varrecordCount=map['recordCount'];//总记录数
- varpageSize=map['pageSize'];//每页显示记录数
- varpageCount=map['pageCount'];//总页数
- varpageStr="当前页:第"+pageNo+"页|";
- pageStr+="总记录数:"+recordCount+"条|";
- pageStr+="每页显示:"+pageSize+"条|";
- pageStr+="总页数:"+pageCount+"页|";
- if(pageNo==1){
- pageStr+="首页上一页";
- }else{
- pageStr+="<ahref="javascript:changtable(1)">首页</a>
- <ahref="javascript:changtable("+(pageNo-1)+")">上一页</a>";
- }
- if(pageNo<pageCount){
- pageStr+="<ahref="javascript:changtable("+(pageNo+1)+")">
- 下一页</a><ahref="javascript:changtable("+pageCount+")">末页</a>";
- }else{
- pageStr+="下一页末页";
- }
- pageStr+=" ";
- pageBar.innerHTML=pageStr;
- }
- //引入dwr的js库文件
- <scripttype='text/javascript'src='dwr/interface/showList.js'></script>
- <scripttype='text/javascript'src='dwr/engine.js'></script>
- <scripttype='text/javascript'src='dwr/util.js'></script>
- //展示列表
- <tablealign="center">
- <tbody>
- <tr>
- <thwidth="28px">
- <inputtype="checkBox"id="allche"value="checkBox"
- title="全选/全不选"onclick="allChoose();changeIds();">
- </th>
- <th>
- 标题
- </th>
- <th>
- 录入者
- </th>
- <th>
- 点击数
- </th>
- </tr>
- </tbody>
- <tbodyid="tablebody">
- </tbody>
- </table>
- <divid="showmsg"align="center">
- </div>
- <divid="pageDiv"align="right">
- </div>
当前页:第 1 页 |总记录数: 21条 |每页显示: 10条 |总页数: 3页 |首页上一页下一页末页
DWR整合SSH大致总结到这里,粘了比较多的代码。希望能给有类似需求的朋友们提供一点点帮助。