加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

DWR3实现服务器端向客户端精确推送消息

发布时间:2020-12-15 21:44:39 所属栏目:百科 来源:网络整理
导读:我这种刚开始学习DWR的人来说要看懂真的蛮难。不过即便如此, http://www.blogjava.net/stevenjohn/archive/2012/07/07/382447.html这片文章还是给了我很大帮助,再次表示感谢,下面我将这两天的研究详细记录下来备忘,也希望能帮助到像我一样的人。只写过程
    我这种刚开始学习DWR的人来说要看懂真的蛮难。不过即便如此, http://www.blogjava.net/stevenjohn/archive/2012/07/07/382447.html这片文章还是给了我很大帮助,再次表示感谢,下面我将这两天的研究详细记录下来备忘,也希望能帮助到像我一样的人。只写过程,不写原理(不是不写,而是有些地方我也不太懂),下面开始:

第一、在项目中引入dwr.jar,然后在web.xml中进行配置,配置如下:

Java代码
  1. <servlet>
  2. <servlet-name>dwr-invoker</servlet-name>
  3. <servlet-class>
  4. org.directwebremoting.servlet.DwrServlet
  5. </servlet-class>
  6. <init-param>
  7. <param-name>crossDomainSessionSecurity</param-name>
  8. <param-value>false</param-value>
  9. </init-param>
  10. <init-param>
  11. <param-name>allowScriptTagRemoting</param-name>
  12. <param-value>true</param-value>
  13. </init-param>
  14. <init-param>
  15. <param-name>classes</param-name>
  16. <param-value>java.lang.Object</param-value>
  17. </init-param>
  18. <init-param>
  19. <param-name>activeReverseAjaxEnabled</param-name>
  20. <param-value>true</param-value>
  21. </init-param>
  22. <init-param>
  23. <param-name>initApplicationScopeCreatorsAtStartup</param-name>
  24. <param-value>true</param-value>
  25. </init-param>
  26. <init-param>
  27. <param-name>maxWaitAfterWrite</param-name>
  28. <param-value>3000</param-value>
  29. </init-param>
  30. <init-param>
  31. <param-name>debug</param-name>
  32. <param-value>true</param-value>
  33. </init-param>
  34. <init-param>
  35. <param-name>logLevel</param-name>
  36. <param-value>WARN</param-value>
  37. </init-param>
  38. </servlet>

第二:在web.xml的同级目录下新建dwr.xml文件,内容如下

Java代码
  1. <!DOCTYPEdwrPUBLIC
  2. "-//GetAheadLimited//DTDDirectWebRemoting3.0//EN"
  3. "http://getahead.org/dwr/dwr30.dtd">
  4. <dwr>
  5. <alow>
  6. <createcreator="new"javascript="MessagePush">
  7. <paramname="class"value="com.huatech.messageremind.service.MessagePush"/>
  8. </create>
  9. <createcreator="new"javascript="TestPush">
  10. <paramname="class"value="com.huatech.messageremind.service.Test"/>
  11. </create>
  12. </alow>
  13. </dwr>

这个是dwr的基本配置,MessagePush在页面的javascript中使用,这个是对被推送页面开放的java类,Test是对推送页面开放的java类。场景:管理员后台登陆,发布一条消息,通过Test推送到后台,后台通过MessagePush推送给指定的用户,当然,至于怎么找到指定的用户,下面会说。

第三,被推送的页面代码

Java代码
  1. <%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
  2. <%
  3. Stringpath=request.getContextPath();
  4. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  7. <html>
  8. <head>
  9. <basehref="<%=basePath%>">
  10. <title>DWRDEMO</title>
  11. <metahttp-equiv="pragma"content="no-cache">
  12. <metahttp-equiv="cache-control"content="no-cache">
  13. <metahttp-equiv="expires"content="0">
  14. <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
  15. <metahttp-equiv="description"content="Thisismypage">
  16. </head>
  17. <scripttype='text/javascript'src='dwr/engine.js'></script>
  18. <scripttype='text/javascript'src='dwr/util.js'></script>
  19. <scripttype="text/javascript"src="dwr/interface/MessagePush.js"></script>
  20. <scripttype="text/javascript">
  21. //通过该方法与后台交互,确保推送时能找到指定用户
  22. functiononPageLoad(){
  23. varuserId='${userinfo.humanid}';
  24. MessagePush.onPageLoad(userId);
  25. }
  26. //推送信息
  27. functionshowMessage(autoMessage){
  28. alert(autoMessage);
  29. }
  30. </script>
  31. <bodyonload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">
  32. ThisismyDWRDEOMpage.<hr>
  33. <br>
  34. <divid="DemoDiv">demo</div>
  35. </body>
  36. </html>

以上代码的简单解释:

页面页面onload的3个函数都是必须的,后两个是dwr的,第一个是将登录用户的userid与对应 的scriptSession进行处理,以便精确推送的时候能找到推送对象

第四 MessagePush类中实现的方法如下:

Java代码
  1. publicvoidonPageLoad(StringuserId){
  2. ScriptSessionscriptSession=WebContextFactory.get().getScriptSession();
  3. scriptSession.setAttribute(userId,userId);
  4. DwrScriptSessionManagerUtildwrScriptSessionManagerUtil=newDwrScriptSessionManagerUtil();
  5. try{
  6. dwrScriptSessionManagerUtil.init();
  7. System.out.println("cacaca");
  8. }catch(ServletExceptione){
  9. e.printStackTrace();
  10. }
  11. }

里面对应的DwrScriptSessionManagerUtil 对应如下:

Java代码
  1. importjavax.servlet.ServletException;
  2. importjavax.servlet.http.HttpSession;
  3. importorg.directwebremoting.Container;
  4. importorg.directwebremoting.ServerContextFactory;
  5. importorg.directwebremoting.WebContextFactory;
  6. importorg.directwebremoting.event.ScriptSessionEvent;
  7. importorg.directwebremoting.event.ScriptSessionListener;
  8. importorg.directwebremoting.extend.ScriptSessionManager;
  9. importorg.directwebremoting.servlet.DwrServlet;
  10. publicclassDwrScriptSessionManagerUtilextendsDwrServlet{
  11. privatestaticfinallongserialVersionUID=-7504612622407420071L;
  12. publicvoidinit()throwsServletException{
  13. Containercontainer=ServerContextFactory.get().getContainer();
  14. ScriptSessionManagermanager=container.getBean(ScriptSessionManager.class);
  15. ScriptSessionListenerlistener=newScriptSessionListener(){
  16. publicvoidsessionCreated(ScriptSessionEventev){
  17. HttpSessionsession=WebContextFactory.get().getSession();
  18. StringuserId=((User)session.getAttribute("userinfo")).getHumanid()+"";
  19. System.out.println("aScriptSessioniscreated!");
  20. ev.getSession().setAttribute("userId",userId);
  21. }
  22. publicvoidsessionDestroyed(ScriptSessionEventev){
  23. System.out.println("aScriptSessionisdistroyed");
  24. }
  25. };
  26. manager.addScriptSessionListener(listener);
  27. }
  28. }

第五 推送页面代码:

Java代码
  1. <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
  2. <%
  3. Stringpath=request.getContextPath();
  4. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  7. <html>
  8. <head>
  9. <basehref="<%=basePath%>">
  10. <title>MyJSP'MyJsp.jsp'startingpage</title>
  11. <metahttp-equiv="pragma"content="no-cache">
  12. <metahttp-equiv="cache-control"content="no-cache">
  13. <metahttp-equiv="expires"content="0">
  14. <metahttp-equiv="keywords"content="keyword1,keyword3">
  15. <metahttp-equiv="description"content="Thisismypage">
  16. <scripttype="text/javascript"src="<%=request.getContextPath()%>/js/jquery-1.5.1.js"></script>
  17. <scripttype='text/javascript'src='dwr/engine.js'></script>
  18. <scripttype='text/javascript'src='dwr/util.js'></script>
  19. <scripttype='text/javascript'src='dwr/interface/TestPush.js'></script>
  20. <scripttype="text/javascript">
  21. functiontest(){
  22. varmsg=document.getElementById("msgId").value;
  23. //msg={msgId:'1',context:$("#msgContext").val()};
  24. TestPush.sendMessageAuto(msg,"哈哈哈");
  25. }
  26. </script>
  27. </head>
  28. <body>
  29. id&nbsp;&nbsp;&nbsp;&nbsp;:<inputtype="text"name="msgId"id="msgId"/><br/>
  30. <inputtype="button"value="Send"onclick="test()"/>
  31. </body>
  32. </html>

第六:精确推送要实现的代码:

Java代码
  1. publicclassTest{
  2. publicvoidsendMessageAuto(Stringuserid,Stringmessage){
  3. finalStringuserId=userid;
  4. finalStringautoMessage=message;
  5. Browser.withAllSessionsFiltered(newScriptSessionFilter(){
  6. publicbooleanmatch(ScriptSessionsession){
  7. if(session.getAttribute("userId")==null)
  8. returnfalse;
  9. else
  10. return(session.getAttribute("userId")).equals(userId);
  11. }
  12. },newRunnable(){
  13. privateScriptBufferscript=newScriptBuffer();
  14. publicvoidrun(){
  15. script.appendCall("showMessage",autoMessage);
  16. Collection<ScriptSession>sessions=Browser
  17. .getTargetSessions();
  18. for(ScriptSessionscriptSession:sessions){
  19. scriptSession.addScript(script);
  20. }
  21. }
  22. });
  23. }
  24. }

至此 这个例子的代码都已经贴出来了,应该是可以跑通的,有问题的话可以给我留言。当然,要自己写个登录,然后把userId放到session里面,这个比较简单,就不贴代码了,有问题可以在http://download.csdn.net/detail/luojia_wang/5275588上下载原项目。我只是简单的做了一个能实现功能的例子,还有很多地方要研究,比如跟spring整合,还可能有很多优化,等我继续学习一下再说.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读