DWR允許客戶端腳本遠程調(diào)用服務(wù)器端的類方法。使用它可以很容易的構(gòu)建ajax程序。在此,簡要說明一下如何通過DWR構(gòu)建一個簡單的一對一聊天程序。

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供察隅網(wǎng)站建設(shè)、察隅做網(wǎng)站、察隅網(wǎng)站設(shè)計、察隅網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、察隅企業(yè)網(wǎng)站模板建站服務(wù),十余年察隅做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
1.首先配置web.xml
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置DwrServlet -->
<display-name>DWR (Direct Web Remoting)</display-name>
<description>A Simple Demo DWR</description>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param><!--開啟debug為true后,可以通過訪問ContextPath/dwr/index.html進行調(diào)試-->
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param><!--該選項為true時,輪詢和反向ajax會被啟用-->
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>initApplicationScopeCreatorsAtStartup</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>maxWaitAfterWrite</param-name>
<param-value>-1</param-value>
</init-param>
<init-param><!--該參數(shù)為true時,允許遠程服務(wù)器將javascript代碼動態(tài)添加到客戶端頁面中-->
<param-name>allowScriptTagRemoting</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<!-- 監(jiān)聽scriptSession -->
<servlet>
<servlet-name>scriptSessionListener</servlet-name>
<servlet-class>com.hb.util.InitScriptSessionListener</servlet-class>
<load-on-startup>8</load-on-startup>
</servlet>2.配置dwr.xml
<create creator="spring" javascript="MessageService" scope="application">
<param name="beanName" value="dwrMessageService"/>
</create>
<convert converter="bean" match="com.entity.Message" />dwr中create元素中creator屬性為spring,表示,名為“dwrMessageService”的bean由spring進行管理,javascript屬性值表示如何在客戶端調(diào)用該bean,即通過該屬性的值調(diào)用。dwr可以自動對javascript對象和java對象進行轉(zhuǎn)化。convert元素的match屬性即表示哪個java bean交由dwr進行互轉(zhuǎn)。
3.spring配置文件如下
<bean id="dwrMessageService" class="com.dwr.MyMessageService" scope="prototype"> <property name="messageService"> <ref bean="messageService"/> </property> </bean>
4.(1)com.dwr.MyMessageService類部分代碼如下:
import com.util.initParam;
public boolean pushMessageToSomeOne(String userId,Message msg){
/*將消息保存到數(shù)據(jù)庫*/
try {
messageService.saveMessage(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//調(diào)用接收方客戶端的showMessageFromOne(msg)函數(shù),將msg消息傳遞給接收方
ScriptBuffer script = new ScriptBuffer(); script.appendScript("showMessageFromOne(").
appendData(msg).appendScript(");");
ScriptSession s1= initParam.sc.get(userId); //獲取接收方的ScriptSession
s1.addScript(script);
return true;
}(2)com.util.initParam類
package com.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.directwebremoting.ScriptSession;
import com.dwr.ScriptSessionAndUser;
public class initParam {
public static Map<String,ScriptSession> sc =newHashMap<String,ScriptSession>(); // 保存用戶id和該用戶對應(yīng)的ScriptSession
public initParam(){}
}(3)用來監(jiān)聽ScriptSession的Servlet:InitScriptSessionListener
package com.util;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import org.directwebremoting.Container;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;
public class InitScriptSessionListener extends GenericServlet {
/* 監(jiān)控ScriptSessionListener狀態(tài)*/
public void init()
{
Container container = ServerContextFactory.get().getContainer();
ScriptSessionManager manager =container.getBean(ScriptSessionManager.class);
ScriptSessionListener listener = new AddScriptSessionListener();
manager.addScriptSessionListener(listener);
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
init();
}
}(4)AddScriptSessionListener類
package com.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
public class AddScriptSessionListener implements ScriptSessionListener{
public void sessionCreated(ScriptSessionEvent se) {
/*客戶端刷新頁面后,將用戶的session信息和ScriptSession重新綁定*/
WebContext ct = WebContextFactory.get();
HttpSession session =ct.getHttpServletRequest().getSession();
initParam.sc.put(session.getAttribute("UsersId").toString(),
se.getSession());
public void sessionDestroyed(ScriptSessionEvent se) {
System.out.println(se.getSession()+"銷毀");
}
}5.客戶端代碼
<script type="text/javascript" src="<%=basePath%>dwr/engine.js"</script>
<script type="text/javascript" src="<%=basePath%>dwr/interface/MessageService.js"></script>
<script type="text/javascript">
dwr.engine.setActiveReverseAjax(true); //啟用dwr反向ajax
dwr.engine.setNotifyServerOnPageUnload(true);//刷新頁面后銷毀當(dāng)前scriptsession
dwr.engine.setErrorHandler(function()
{
//alert("錯誤");
}); //自定義錯誤處理方式
function sendMessageTo(userId)
{
var content=document.getElementById("content").innerHTML;
document.getElementById("content").innerHTML="";
document.getElementById("message").innerHTML=getId("message").innerHTML+"<li><span>${session.username}"+content+"</span></li>";
var msg={};
msg.getId=userId;
msg.content=content;
msg.sendId=${session.userId};//將發(fā)送的信息顯示到信息框
MessageService.pushMessageToSomeOne(userId,msg,function(data){});
//通過MessageService對象調(diào)用遠程MyMessageService類的 public boolean pushMessageToSomeOne(String userId,Message msg)方法,最后一個參數(shù)為回調(diào)函數(shù)
}
function showMessageFromOne(msg)
{ var htmls="<li><span>"+msg.sendId+"+msg.content+"</span></li>"; document.getElementById("message").innerHTML=document.getElementById("message").innerHTML+htmls+"<br />";
}
}<script type="text/javascript" src="<%=basePath%>dwr/engine.js"</script>
<script type="text/javascript" src="<%=basePath%>dwr/interface/MessageService.js"></script>
<script type="text/javascript">
dwr.engine.setActiveReverseAjax(true); //啟用dwr反向ajax
dwr.engine.setNotifyServerOnPageUnload(true);//刷新頁面后銷毀當(dāng)前scriptsession
dwr.engine.setErrorHandler(function()
{
//alert("錯誤");
}); //自定義錯誤處理方式
function sendMessageTo(userId)
{
var content=document.getElementById("content").innerHTML;
document.getElementById("content").innerHTML="";
document.getElementById("message").innerHTML=getId("message").innerHTML+"<li><span>${session.username}"+content+"</span></li>";
var msg={};
msg.getId=userId;
msg.content=content;
msg.sendId=${session.userId};//將發(fā)送的信息顯示到信息框
MessageService.pushMessageToSomeOne(userId,msg,function(data){});
//通過MessageService對象調(diào)用遠程MyMessageService類的 public boolean pushMessageToSomeOne(String userId,Message msg)方法,最后一個參數(shù)為回調(diào)函數(shù)
}
}<div id="container">
<div id="message"></div>
<div id="content"></div>
<input type="button" data-role="button" onclick="sendMessageTo(${getUsers.id})">發(fā)送</a>
</div>6.現(xiàn)在解釋一下ScriptSession.我們知道,一般的Session會在用戶初次訪問時創(chuàng)建,然后在用戶的整個訪問過程中一直存在,直到用戶在一定時間內(nèi)未進行任何訪問后銷毀。 而DWR中的ScriptSession則是用戶每次刷新或重新請求一個dwr控制的頁面時,重新創(chuàng)建。因此,在本例中我們創(chuàng)建了ScriptSession的監(jiān)聽器,每當(dāng)重新創(chuàng)建新的ScriptSession時,將當(dāng)前用戶的session與新的ScriptSession重新綁定,以便可以確切的將消息發(fā)送給目標(biāo)用戶,而不是調(diào)用一個已經(jīng)不存在的ScriptSession。 通過在頁面加載后調(diào)用dwr.engine.setNotifyServerOnPageUnload(true);可以使DWR在創(chuàng)建一個新的ScriptSession后自動銷毀之前的ScriptSession。
7.本例是本人在測試的項目當(dāng)中挖取的一部分主要內(nèi)容,可能不夠全面,也存在一些問題。望大家批評指正。謝謝。
本文標(biāo)題:DWR構(gòu)建的簡單聊天程序-供初學(xué)者學(xué)習(xí)
文章URL:http://www.chinadenli.net/article44/jdheee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機網(wǎng)站建設(shè)、用戶體驗、企業(yè)網(wǎng)站制作、電子商務(wù)、網(wǎng)站設(shè)計公司、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)