您好,登錄后才能下訂單哦!
DWR允許客戶端腳本遠程調用服務器端的類方法。使用它可以很容易的構建ajax程序。在此,簡要說明一下如何通過DWR構建一個簡單的一對一聊天程序。
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進行調試--> <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><!--該參數為true時,允許遠程服務器將javascript代碼動態添加到客戶端頁面中--> <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> <!-- 監聽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屬性值表示如何在客戶端調用該bean,即通過該屬性的值調用。dwr可以自動對javascript對象和java對象進行轉化。convert元素的match屬性即表示哪個java bean交由dwr進行互轉。
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){ /*將消息保存到數據庫*/ try { messageService.saveMessage(msg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //調用接收方客戶端的showMessageFromOne(msg)函數,將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和該用戶對應的ScriptSession public initParam(){} }
(3)用來監聽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 { /* 監控ScriptSessionListener狀態*/ 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);//刷新頁面后銷毀當前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};//將發送的信息顯示到信息框 MessageService.pushMessageToSomeOne(userId,msg,function(data){}); //通過MessageService對象調用遠程MyMessageService類的 public boolean pushMessageToSomeOne(String userId,Message msg)方法,最后一個參數為回調函數 } 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);//刷新頁面后銷毀當前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};//將發送的信息顯示到信息框 MessageService.pushMessageToSomeOne(userId,msg,function(data){}); //通過MessageService對象調用遠程MyMessageService類的 public boolean pushMessageToSomeOne(String userId,Message msg)方法,最后一個參數為回調函數 } }
<div id="container"> <div id="message"></div> <div id="content"></div> <input type="button" data-role="button" onclick="sendMessageTo(${getUsers.id})">發送</a> </div>
6.現在解釋一下ScriptSession.我們知道,一般的Session會在用戶初次訪問時創建,然后在用戶的整個訪問過程中一直存在,直到用戶在一定時間內未進行任何訪問后銷毀。 而DWR中的ScriptSession則是用戶每次刷新或重新請求一個dwr控制的頁面時,重新創建。因此,在本例中我們創建了ScriptSession的監聽器,每當重新創建新的ScriptSession時,將當前用戶的session與新的ScriptSession重新綁定,以便可以確切的將消息發送給目標用戶,而不是調用一個已經不存在的ScriptSession。 通過在頁面加載后調用dwr.engine.setNotifyServerOnPageUnload(true);可以使DWR在創建一個新的ScriptSession后自動銷毀之前的ScriptSession。
7.本例是本人在測試的項目當中挖取的一部分主要內容,可能不夠全面,也存在一些問題。望大家批評指正。謝謝。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。