Java Dwr3实现消息推送步骤详解

1、在工程中引入dwr.jar,之后修改配置web.xml文件,添加配置具体代码如下:

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>

2、在web.xml统计目录下新增dwr.xml文件,具体内容如下:

1<!DOCTYPE dwr PUBLIC 2          "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" 3          "http://getahead.org/dwr/dwr30.dtd"> 4     <dwr> 5          <alow> 6               <create creator="new" javascript="MessagePush"> 7                 <param name="class" value="com.yoodb.service.MessagePush"/> 8              </create> 9       <create creator="new" javascript="TestPush">   10                  <param name="class" value="com.yoodb.service.TestPush"/>   11              </create> 12          </alow> 13     </dwr>

MessagePush在页面的javascript中使用,com.yoodb.service.MessagePush实现了想要调用的方法,其中MessagePush.java对被推送页面开放的java类,Test.java是对推送页面开放的java类。在javascript中使用MessagePush.java类中实现的方法,即可在dwr中调用。

3、引入JavaScript文件,具体如下:

1<script type="text/javascript" src="<%=basepath%>dwr/engine.js"></script> 2<script type="text/javascript" src="<%=basepath%>dwr/util.js"></script> 3<script type="text/javascript" src="<%=basepath%>dwr/interface/MessagePush.js"></script>

注意:

1)dwr.xml配置的javascript中engine.js和util.js是必须引入的文件。

2)在任何一个用户登录的时候,都需要将其userId或者其他唯一性标识放入session中,我放的是userId,这里就以userId为唯一性标识。

3)在载入想推送的页面时,需要onload一个我在MessagePush类中实现的方法,当然了,需要使用dwr调用

被推送html页面具体内容代码如下:

1<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>   2<%   3String path = request.getContextPath();   4String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   5%>   6<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   7<html>   8  <head>   9    <base href="<%=basePath%>">   10    <title>DWR  DEMO</title>   11    <meta http-equiv="pragma" content="no-cache">   12    <meta http-equiv="cache-control" content="no-cache">   13    <meta http-equiv="expires" content="0">       14    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   15    <meta http-equiv="description" content="This is my page">   16  </head>   17  <script type='text/javascript' src='dwr/engine.js'></script>   18  <script type='text/javascript' src='dwr/util.js'></script>   19  <script type="text/javascript" src="dwr/interface/MessagePush.js"></script>   20   21  <script type="text/javascript">   22        //通过该方法与后台交互,确保推送时能找到指定用户   23         function onPageLoad(){   24            var userId = '${userinfo.userId}';   25            MessagePush.onPageLoad(userId);   26          }   27         //推送信息   28         function showMessage(autoMessage){   29                alert(autoMessage);       30        }   31  </script>   32  <body onload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">    33    This is my DWR DEOM page. <hr>   34    <br>   35    <div id="DemoDiv">demo</div>   36  </body>   37</html>

其中MessagePush.java文件中实现方法,如下:

1public class MessagePush{   2 public void onPageLoad(String userId) {   3        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();   4        scriptSession.setAttribute(userId, userId);   5        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();   6        try {   7               dwrScriptSessionManagerUtil.init();   8               System.out.println("cacaca");   9        } catch (ServletException e) {   10               e.printStackTrace();   11        }   12 }   13}

对于onPageLoad()方法中DwrScriptSessionManagerUtil类的实现,具体如下:

1import javax.servlet.ServletException;   2import javax.servlet.http.HttpSession;   3   4import org.directwebremoting.Container;   5import org.directwebremoting.ServerContextFactory;   6import org.directwebremoting.WebContextFactory;   7import org.directwebremoting.event.ScriptSessionEvent;   8import org.directwebremoting.event.ScriptSessionListener;   9import org.directwebremoting.extend.ScriptSessionManager;   10import org.directwebremoting.servlet.DwrServlet;   11   12public class DwrScriptSessionManagerUtil extends DwrServlet{   13   14    private static final long serialVersionUID = -7504612622407420071L;   15   16    public void init()throws ServletException {   17   18           Container container = ServerContextFactory.get().getContainer();   19           ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);   20           ScriptSessionListener listener = new ScriptSessionListener() {   21                  public void sessionCreated(ScriptSessionEvent ev) {   22                         HttpSession session = WebContextFactory.get().getSession();   23   24                         String userId =((User) session.getAttribute("userinfo")).getHumanid()+"";   25                         System.out.println("a ScriptSession is created!");   26                         ev.getSession().setAttribute("userId", userId);   27                  }   28                  public void sessionDestroyed(ScriptSessionEvent ev) {   29                         System.out.println("a ScriptSession is distroyed");   30                  }   31           };   32           manager.addScriptSessionListener(listener);   33    }   34}

4、推送html页面具体内容代码如下:

1<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   2<%   3String path = request.getContextPath();   4String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   5%>   6<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   7<html>   8  <head>   9    <base href="<%=basePath%>">   10    <title>My JSP 'MyJsp.jsp' starting page</title>   11    <meta http-equiv="pragma" content="no-cache">   12    <meta http-equiv="cache-control" content="no-cache">   13    <meta http-equiv="expires" content="0">       14    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   15    <meta http-equiv="description" content="This is my page">   16    <script type='text/javascript' src='dwr/engine.js'></script>   17    <script type='text/javascript' src='dwr/util.js'></script>   18    <script type='text/javascript' src='dwr/interface/TestPush.js'></script>   19       20    <script type="text/javascript">   21       22    function testPush() {   23        var msg = document.getElementById("msgId").value;   24        TestPush.sendMessageAuto(msg,"www.yoodb.com");   25           26    }   27    </script>   28  </head>   29     30  <body>   31    id值: <input type="text" name="msgId" id="msgId" /> <br />   32    <input type="button" value="Send" onclick="testPush()"  />   33  </body>   34</html>

其中TeshPush.java文件,具体内容如下:

1public class TestPush{   2    public void sendMessageAuto(String userid, String message){   3           4        final String userId = userid;   5        final String autoMessage = message;   6        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {   7            public boolean match(ScriptSession session){   8                if (session.getAttribute("userId") == null)   9                    return false;   10                else   11                    return (session.getAttribute("userId")).equals(userId);   12            }   13        }, new Runnable(){   14               15            private ScriptBuffer script = new ScriptBuffer();   16               17            public void run(){   18                   19                script.appendCall("showMessage", autoMessage);   20                   21                Collection<ScriptSession> sessions = Browser   22   23                .getTargetSessions();   24                   25                for (ScriptSession scriptSession : sessions){   26                    scriptSession.addScript(script);   27                }   28            }   29        });   30    }   31}
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java代码032

code033.jsp获取web.xml中的配置<%在tomcat的web.xml配置文件中,增加如下配置:urljdbc:mysql://127.0.0.1:3306/test%

Spring的JNDI数据源连接池配置示例及Spring对JNDI实现分析

在使用Tomcat服务器SpringFramework进行JavaEE项目的开发部署的时候可以在Tomcat的配置文件中进行JDBC数据源的配置,具体步骤如下(这里省略了工程的建立步骤):1)添加如下代码到tomcat的conf目录下的server.xml中:Xml代码 收藏代码<Context

CXF隐藏restful接口列表页面

隐藏所有在CXFServlet(web.xml)处设定hideservicelistpage<servlet<servletnameCXFServlet</servletname<servletclassorg.apache.cxf.transport.servlet.C

KVM调整cpu和内存

一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid

JavaWeb学习总结(四十八)——模拟Servlet3.0使用注解的方式配置Servlet

一、Servlet的传统配置方式  在JavaWeb开发中,每次编写一个Servlet都需要在web.xml文件中进行配置,如下所示:1<servlet2<servletnameActionServlet</servletname3<servletcla