研究了一天半,終於模擬出了這個功能,網上DWR的資料不少,但是真正實現客戶端向服務器端精確推送消息的只有兩篇文章。但是代碼都只有一部分,向我這種剛開始學習DWR的人來說要看懂真的蠻難。不過即便如此,http://www.blogjava.net/stevenjohn/archive/2012/07/07/382447.html這片文章還是給了我很大幫助,再次表示感謝,下面我將這兩天的研究詳細記錄下來備忘,也希望能幫助到像我一樣的人。只寫過程,不寫原理(不是不寫,而是有些地方我也不太懂),下面開始:
第一、在項目中引入dwr.jar,然後在web.xml中進行配置,配置如下:
- <servlet>
- <servlet-name>dwr-invoker</servlet-name>
- <servlet-class>
- org.directwebremoting.servlet.DwrServlet
- </servlet-class>
- <init-param>
- <param-name>crossDomainSessionSecurity</param-name>
- <param-value>false</param-value>
- </init-param>
- <init-param>
- <param-name>allowScriptTagRemoting</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>classes</param-name>
- <param-value>java.lang.Object</param-value>
- </init-param>
- <init-param>
- <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>3000</param-value>
- </init-param>
- <init-param>
- <param-name>debug</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>logLevel</param-name>
- <param-value>WARN</param-value>
- </init-param>
- </servlet>
第二:在web.xml的同級目錄下新建dwr.xml文件,內容如下
- <!DOCTYPE dwr PUBLIC
- "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
- "http://getahead.org/dwr/dwr30.dtd">
- <dwr>
- <alow>
- <create creator="new" javascript="MessagePush">
- <param name="class" value="com.huatech.messageremind.service.MessagePush"/>
- </create>
- <create creator="new" javascript="TestPush">
- <param name="class" value="com.huatech.messageremind.service.Test"/>
- </create>
- </alow>
- </dwr>
這個是dwr的基本配置,MessagePush在頁面的javascript中使用,這個是對被推送頁面開放的java類,Test是對推送頁面開放的java類。場景:管理員後臺登陸,發佈一條消息,通過Test推送到後臺,後臺通過MessagePush推送給指定的用戶,當然,至於怎麼找到指定的用戶,下面會說。
第三,被推送的頁面代碼
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>DWR DEMO</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <script type='text/javascript' src='dwr/engine.js'></script>
- <script type='text/javascript' src='dwr/util.js'></script>
- <script type="text/javascript" src="dwr/interface/MessagePush.js"></script>
- <script type="text/javascript">
- //通過該方法與後臺交互,確保推送時能找到指定用戶
- function onPageLoad(){
- var userId = '${userinfo.humanid}';
- MessagePush.onPageLoad(userId);
- }
- //推送信息
- function showMessage(autoMessage){
- alert(autoMessage);
- }
- </script>
- <body onload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">
- This is my DWR DEOM page. <hr>
- <br>
- <div id="DemoDiv">demo</div>
- </body>
- </html>
以上代碼的簡單解釋:
頁面頁面onload的3個函數都是必須的,後兩個是dwr的,第一個是將登錄用戶的userid與對應 的scriptSession進行處理,以便精確推送的時候能找到推送對象
第四 MessagePush類中實現的方法如下:
- public void onPageLoad(String userId) {
- ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
- scriptSession.setAttribute(userId, userId);
- DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
- try {
- dwrScriptSessionManagerUtil.init();
- System.out.println("cacaca");
- } catch (ServletException e) {
- e.printStackTrace();
- }
- }
裏面對應的DwrScriptSessionManagerUtil 對應如下:
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpSession;
- import org.directwebremoting.Container;
- import org.directwebremoting.ServerContextFactory;
- import org.directwebremoting.WebContextFactory;
- import org.directwebremoting.event.ScriptSessionEvent;
- import org.directwebremoting.event.ScriptSessionListener;
- import org.directwebremoting.extend.ScriptSessionManager;
- import org.directwebremoting.servlet.DwrServlet;
- public class DwrScriptSessionManagerUtil extends DwrServlet{
- private static final long serialVersionUID = -7504612622407420071L;
- public void init()throws ServletException {
- Container container = ServerContextFactory.get().getContainer();
- ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
- ScriptSessionListener listener = new ScriptSessionListener() {
- public void sessionCreated(ScriptSessionEvent ev) {
- HttpSession session = WebContextFactory.get().getSession();
- String userId =((User) session.getAttribute("userinfo")).getHumanid()+"";
- System.out.println("a ScriptSession is created!");
- ev.getSession().setAttribute("userId", userId);
- }
- public void sessionDestroyed(ScriptSessionEvent ev) {
- System.out.println("a ScriptSession is distroyed");
- }
- };
- manager.addScriptSessionListener(listener);
- }
- }
第五 推送頁面代碼:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'MyJsp.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.5.1.js"></script>
- <script type='text/javascript' src='dwr/engine.js'></script>
- <script type='text/javascript' src='dwr/util.js'></script>
- <script type='text/javascript' src='dwr/interface/TestPush.js'></script>
- <script type="text/javascript">
- function test() {
- var msg = document.getElementById("msgId").value;
- //msg = {msgId: '1', context: $("#msgContext").val()};
- TestPush.sendMessageAuto(msg,"哈哈哈");
- }
- </script>
- </head>
- <body>
- id : <input type="text" name="msgId" id="msgId" /> <br />
- <input type="button" value="Send" onclick="test()" />
- </body>
- </html>
第六:精確推送要實現的代碼:
- public class Test{
- public void sendMessageAuto(String userid, String message){
- final String userId = userid;
- final String autoMessage = message;
- Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
- public boolean match(ScriptSession session){
- if (session.getAttribute("userId") == null)
- return false;
- else
- return (session.getAttribute("userId")).equals(userId);
- }
- }, new Runnable(){
- private ScriptBuffer script = new ScriptBuffer();
- public void run(){
- script.appendCall("showMessage", autoMessage);
- Collection<ScriptSession> sessions = Browser
- .getTargetSessions();
- for (ScriptSession scriptSession : sessions){
- scriptSession.addScript(script);
- }
- }
- });
- }
- }
至此 這個例子的代碼都已經貼出來了,應該是可以跑通的,有問題的話可以給我留言。當然,要自己寫個登錄,然後把userId放到session裏面,這個比較簡單,就不貼代碼了,有問題可以在http://download.csdn.net/detail/luojia_wang/5275588上下載原項目。我只是簡單的做了一個能實現功能的例子,還有很多地方要研究,比如跟spring整合,還可能有很多優化,等我繼續學習一下再說.