項目需要用到Ajax,最開始本想用Jquery,最后權(quán)衡下選擇了DWR。
這里說的是DWR整合SSH,其實DWR完全沒有必要和Struts2結(jié)合,畢竟DWR需要返回的是Object,而Struts2直接轉(zhuǎn)向了頁面。非要強制將二者整合,只能做一個偽Action,這個偽Action返回的還是Object。當(dāng)然DWR和Spring、Hibernate結(jié)合就非常好,可以將Struts2戲稱為小三了 O(∩_∩)O ~
扯得有點遠(yuǎn)了,步入正題。
需求描述:
根據(jù)新聞標(biāo)題(title)利用Ajax模糊查詢新聞集合(這里將這些新聞集合稱之為 相關(guān)新聞),并將得到的相關(guān)新聞在頁面以列表的形式展示出來,且需要實現(xiàn)分頁。
框架搭建(這里只講與DWR有關(guān)的配置,DWR--Version: 2.0.1)à
web.xml:
view plaincopy to clipboardprint?
01.<listener>
02.<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
03.</listener>
04.<servlet>
05. <servlet-name>dwr-invoker</servlet-name>
06.<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
07. <init-param>
08. <param-name>debug</param-name>
09. <param-value>true</param-value>
10. </init-param>
11.</servlet>
12.<servlet-mapping>
13. <servlet-name>dwr-invoker</servlet-name>
14. <url-pattern>/dwr/*</url-pattern>
15.</servlet-mapping>
<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配置文件:
dwr的spring配置文件(這里將其單獨作為一個配置文件,需將其import到applicationContext.xml內(nèi),這里將偽action交于spring代管):
新聞Bean(只列舉出頁面列表迭代用到的字段):
view plaincopy to clipboardprint?
01.private String title;//標(biāo)題
02.private String creater;//錄入人
03.private int checks;//點擊數(shù)
private String title;//標(biāo)題
private String creater;//錄入人
private int checks;//點擊數(shù)
dwr package:
由于service只是簡單的dao的引用,所以這里只列出核心的兩個類: DWRQueryDaoImpl 和DWRQuery (DWRQuery--這個偽Action的小三)
DWRQueryDaoImpl:
view plaincopy to clipboardprint?
01.public class DWRQueryDaoImpl extends HibernateDaoSupport implements DWRQueryDao {
02.
03. //此方法用于普通查詢
04. public List<News> getNewsListByTitle(String title){
05. try {
06. String hql="from News as o where o.title like '%"+title.trim()+"%';
07. return (List<News>)super.getHibernateTemplate().find(hql);
08. } catch (RuntimeException re) {
09. throw re;
10. }
11. }
12.
13. //此方法用于dwr分頁查詢,其實質(zhì)用的還是Hibernate的分頁技術(shù)
14. //pageNo :當(dāng)前頁數(shù)
15. //pagesize:每頁顯示的記錄數(shù)
16. public List<News> getNewsListByPage(final String title, final int pageNo,final int pagesize){
17. final Map<String,List<News>> map=new HashMap<String,List<News>>();
18. try {
19. super.getHibernateTemplate().execute(new HibernateCallback<List<News>>()
20. {
21. public List<News> doInHibernate(Session session) throws HibernateException, SQLException
22. {
23. String hql="from News as o where o.title like '%"+title.trim()+"%';
24. Query query = session.createQuery(hql);
25.
26. int firstindex=(pageNo-1)*pagesize;
27. query.setFirstResult(firstindex).setMaxResults(pagesize);
28.
29. List list= query.list();
30. map.put("map",list);
31. return null;
32. }
33.
34. });
35. List returnList=map.get("map");
36. return returnList;
37. } catch (RuntimeException re) {
38. throw re;
39. }
40. }
41.}
public class DWRQueryDaoImpl extends HibernateDaoSupport implements DWRQueryDao {
//此方法用于普通查詢
public List<News> getNewsListByTitle(String title){
try {
String hql="from News as o where o.title like '%"+title.trim()+"%';
return (List<News>)super.getHibernateTemplate().find(hql);
} catch (RuntimeException re) {
throw re;
}
}
//此方法用于dwr分頁查詢,其實質(zhì)用的還是Hibernate的分頁技術(shù)
//pageNo :當(dāng)前頁數(shù)
//pagesize:每頁顯示的記錄數(shù)
public List<News> getNewsListByPage(final String title, 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()+"%';
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:
view plaincopy to clipboardprint?
01.public class DWRQuery {
02. private DWRQueryService qes; //service
03. private String title;//
04. private int pagesize=10;//默認(rèn)每頁顯示10條記錄
05.
06. /**
07. * DWR 進行相關(guān)新聞分頁顯示
08. * pageNo 頁碼,從 1 開始
09. * pageSize 每頁的記錄數(shù)
10. * 此處返回的是Map
11. */
12. @SuppressWarnings("unchecked")
13. public Map dwrQuery(String title, int pageNo){
14. List<News> list=new ArrayList<News>();
15. list=qes.getNewsListByTitle(title, colid);
16. //獲得總記錄數(shù)
17. Integer recordCount=list.size();
18. //總頁數(shù)
19. int pageCount=(int)Math.ceil(recordCount.doubleValue()/this.getPagesize());
20.
21. list.clear();
22. list=qes.getNewsListByPage(title, pageNo, this.getPagesize());
23. Map map=new HashMap();
24. map.put("recordCount", recordCount);//總記錄數(shù)
25. map.put("pageSize", this.getPagesize());//每頁顯示數(shù)
26. map.put("pageCount", pageCount);//總頁數(shù)
27. map.put("dataList", list);//相關(guān)新聞集合
28.
29. return map;
30. }
31.//setter and getter ……
32.}
public class DWRQuery {
private DWRQueryService qes; //service
private String title;//
private int pagesize=10;//默認(rèn)每頁顯示10條記錄
/**
* DWR 進行相關(guān)新聞分頁顯示
* pageNo 頁碼,從 1 開始
* pageSize 每頁的記錄數(shù)
* 此處返回的是Map
*/
@SuppressWarnings("unchecked")
public Map dwrQuery(String title, int pageNo){
List<News> list=new ArrayList<News>();
list=qes.getNewsListByTitle(title, colid);
//獲得總記錄數(shù)
Integer recordCount=list.size();
//總頁數(shù)
int pageCount=(int)Math.ceil(recordCount.doubleValue()/this.getPagesize());
list.clear();
list=qes.getNewsListByPage(title, pageNo, this.getPagesize());
Map map=new HashMap();
map.put("recordCount", recordCount);//總記錄數(shù)
map.put("pageSize", this.getPagesize());//每頁顯示數(shù)
map.put("pageCount", pageCount);//總頁數(shù)
map.put("dataList", list);//相關(guān)新聞集合
return map;
}
//setter and getter ……
}
頁面展示.jsp(只列出了DWR用到的JS和相關(guān)新聞?wù)故玖斜恚?/div>
view plaincopy to clipboardprint?
01.<!-- DWR JS-->
02. <script type="text/javascript">
03.
04. currentPage=1;//當(dāng)前頁碼全局變量
05. function changtable(pageNo){
06. if(pageNo<1){
07. pageNo=1;//當(dāng)前頁為1
08. }
09. currentPage=pageNo;//根據(jù)當(dāng)前頁數(shù)修改全局變量
10. var querytitle=document.getElementById("querytitle");//這里是查詢字段
11. //這里調(diào)用DWRQuery的dwrQuery方法
12. showList.dwrQuery(querytitle.value,pageNo,callBackMethod);
13. }
14.
15. function callBackMethod(map){
16. var showmsg=document.getElementById("showmsg");
17. var colname=document.getElementById("colname").value;
18. showmsg.innerHTML="";
19. DWRUtil.removeAllRows("tablebody");
20. //沒有查詢到相應(yīng)記錄
21. if(map['dataList'].length==0){
22. showmsg.innerHTML="<font color='red'>沒有查詢到相應(yīng)記錄!</font>";
23. } else{
24. //這里調(diào)用的DWRUtil.addRows方法可以參考我的上一篇文章
25. DWRUtil.addRows("tablebody",map['dataList'],
26. [
27. function(item){
28. return " <input type='checkbox' name='checkbox' value='"+item.id+ "' />"
29. },
30. function(item){
31.return " <a target='_blank' href="pubnews!looknew.action?id="+item.id+"'>" +item.title+"</a>"
32.
33. },
34. function(item){return " "+item.creater},
35. function(item){return " "+item.checks}
36. ],
37. {escapeHtml:false} );
38. }
39.
40. showPageBar(map,currentPage);//根據(jù) 全局當(dāng)前頁數(shù) 調(diào)用顯示頁面導(dǎo)航的函數(shù)
41.}
42.
43.
44. //顯示頁碼導(dǎo)航
45. function showPageBar(map,pageNo){
46. var pageBar=document.getElementById("pageDiv");
47. var recordCount=map['recordCount'];//總記錄數(shù)
48. var pageSize=map['pageSize'];//每頁顯示記錄數(shù)
49. var pageCount=map['pageCount'];//總頁數(shù)
50. var pageStr="當(dāng)前頁:第 "+pageNo+" 頁 | ";
51. pageStr+="總記錄數(shù): "+recordCount+" 條 | ";
52. pageStr+="每頁顯示: "+pageSize+" 條 | ";
53. pageStr+="總頁數(shù): "+pageCount+" 頁 | ";
54. if(pageNo==1){
55. pageStr += "首 頁 上一頁 ";
56. }else{
57. pageStr += "<a href="javascript:changtable(1)" >首 頁</a>
58. <a href="javascript:changtable("+(pageNo-1)+")" >上一頁</a> ";
59. }
60. if(pageNo < pageCount){
61. pageStr += "<a href="javascript:changtable("+(pageNo+1)+")" >
62. 下一頁</a> <a href="javascript:changtable("+pageCount+")" >末 頁</a> ";
63. }else{
64. pageStr += "下一頁 末 頁 ";
65. }
66. pageStr += " ";
67. pageBar.innerHTML= pageStr;
68. }
69.// 引入dwr的js庫文件
70.<script type='text/javascript' src='dwr/interface/showList.js'></script>
71.<script type='text/javascript' src='dwr/engine.js'></script>
72.<script type='text/javascript' src='dwr/util.js'></script>
73.//展示列表
74. <table align="center">
75. <tbody>
76. <tr>
77. <th width="28px">
78. <input type="checkbox" id="allche" value="checkbox"
79. title="全選/全不選" onclick="allChoose();changeIds();">
80. </th>
81. <th >
82. 標(biāo)題
83. </th>
84. <th >
85. 錄入者
86. </th>
87. <th >
88. 點擊數(shù)
89. </th>
90. </tr>
91. </tbody>
92. <tbody id="tablebody">
93. </tbody>
94. </table>
95. <div id="showmsg" align="center">
96. </div>
97. <div id="pageDiv" align="right">
98. </div>
<!-- DWR JS-->
<script type="text/javascript">
currentPage=1;//當(dāng)前頁碼全局變量
function changtable(pageNo){
if(pageNo<1){
pageNo=1;//當(dāng)前頁為1
}
currentPage=pageNo;//根據(jù)當(dāng)前頁數(shù)修改全局變量
var querytitle=document.getElementById("querytitle");//這里是查詢字段
//這里調(diào)用DWRQuery的dwrQuery方法
showList.dwrQuery(querytitle.value,pageNo,callBackMethod);
}
function callBackMethod(map){
var showmsg=document.getElementById("showmsg");
var colname=document.getElementById("colname").value;
showmsg.innerHTML="";
DWRUtil.removeAllRows("tablebody");
//沒有查詢到相應(yīng)記錄
if(map['dataList'].length==0){
showmsg.innerHTML="<font color='red'>沒有查詢到相應(yīng)記錄!</font>";
} else{
//這里調(diào)用的DWRUtil.addRows方法可以參考我的上一篇文章
DWRUtil.addRows("tablebody",map['dataList'],
[
function(item){
return " <input type='checkbox' name='checkbox' value='"+item.id+ "' />"
},
function(item){
return " <a target='_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);//根據(jù) 全局當(dāng)前頁數(shù) 調(diào)用顯示頁面導(dǎo)航的函數(shù)
}
//顯示頁碼導(dǎo)航
function showPageBar(map,pageNo){
var pageBar=document.getElementById("pageDiv");
var recordCount=map['recordCount'];//總記錄數(shù)
var pageSize=map['pageSize'];//每頁顯示記錄數(shù)
var pageCount=map['pageCount'];//總頁數(shù)
var pageStr="當(dāng)前頁:第 "+pageNo+" 頁 | ";
pageStr+="總記錄數(shù): "+recordCount+" 條 | ";
pageStr+="每頁顯示: "+pageSize+" 條 | ";
pageStr+="總頁數(shù): "+pageCount+" 頁 | ";
if(pageNo==1){
pageStr += "首 頁 上一頁 ";
}else{
pageStr += "<a href="javascript:changtable(1)" >首 頁</a>
<a href="javascript:changtable("+(pageNo-1)+")" >上一頁</a> ";
}
if(pageNo < pageCount){
pageStr += "<a href="javascript:changtable("+(pageNo+1)+")" >
下一頁</a> <a href="javascript:changtable("+pageCount+")" >末 頁</a> ";
}else{
pageStr += "下一頁 末 頁 ";
}
pageStr += " ";
pageBar.innerHTML= pageStr;
}
// 引入dwr的js庫文件
<script type='text/javascript' src='dwr/interface/showList.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
//展示列表
<table align="center">
<tbody>
<tr>
<th width="28px">
<input type="checkbox" id="allche" value="checkbox"
title="全選/全不選" onclick="allChoose();changeIds();">
</th>
<th >
標(biāo)題
</th>
<th >
錄入者
</th>
<th >
點擊數(shù)
</th>
</tr>
</tbody>
<tbody id="tablebody">
</tbody>
</table>
<div id="showmsg" align="center">
</div>
<div id="pageDiv" align="right">
</div>
//最終實現(xiàn)的分頁效果
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。