1.pom.xml
<dependency> <groupId>org.directwebremoting</groupId> <artifactId>dwr</artifactId> <version>3.0.2-RELEASE</version> </dependency>
2.web.xml
<servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>pollAndCometEnabled</param-name> //推送方式 <param-value>true</param-value> </init-param> <init-param> <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
备注:
pollAndCometEnabled是指dwr 的reverse ajax是使用polling 和comet的方式,在这个例子中可以明显地从页面上看出来是用的polling+comet
附:关于reverse-ajax的实现有3种方式
polling 就是隔一段时间向服务器发送一request来检查服务端是否有数据更新
comet 就是一个长http请求,在请求期间服务端可以向客户端push数据,但是这种做法要求server和brower长期建立一个通信通道,而且效率很低
piggyback 就是服务端的更新数据都在排队等待,等到下一次有请求过来,那么这些等待更新数据就伴随这次请求一起发送到brower
3.新建dwr.xml
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> <dwr> <allow> <!-- 显示异常 --> <convert converter="bean" match="java.lang.StackTraceElement" /> <convert converter="exception" match="java.lang.Exception" /> <create creator="new" javascript="ProtocolDwrUtils" scope="application" > // create是只一个java的js映射,可以在js使用的方法 <param name="class" value="com.weichai.modules.task.dwrUtil.ProtocolDwrUtils"/> //需要暴露的类 <include method="sendProtocolToPage"/> //类中方法 <include method="onPageLoad"/>//类中方法 </create> </allow> </dwr>
4.新建类ProtocolDwrUtils.java
package com.weichai.modules.task.dwrUtil; import org.directwebremoting.*; import java.util.Collection; /** * Created by ltx on 2017/10/17. */ public class ProtocolDwrUtils { public void sendProtocolToPage(final String params, final String userId) { Browser.withAllSessionsFiltered(new ScriptSessionFilter() { public boolean match(ScriptSession session) { //过滤器,制定userid推送 if (session.getAttribute(userId) != null) { session.removeAttribute(userId); return true; } else { return false; } } }, new Runnable() { private ScriptBuffer script = new ScriptBuffer(); public void run() { script.appendCall("helloWord", params); //前台js方法和参数 Collection<ScriptSession> sessions = Browser.getTargetSessions();//获取所有与服务器相连的浏览器的session for (ScriptSession scriptSession : sessions) { scriptSession.addScript(script); //推送 } } }); } //将前台穿过来的userID存到session中去,后边用作精确推送使用 public void onPageLoad(final String userId){ //获取当前的ScriptSession ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); scriptSession.setAttribute( userId, "1"); System.out.println("onPageLoad----"+userId); } }
5.新建dwrTest.jsp
<%@ page contentType="text/html;charset=UTF-8" %> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html > <head> <meta name="decorator" content="default"/> <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script> <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script> <script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/ProtocolDwrUtils.js'> </script> </head> <body οnlοad="initDwr()"> <script type="text/javascript"> //生成随机字符串 function randomString(len) { len = len || 32; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ var maxPos = $chars.length; var pwd = ''; for (i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } function initDwr(){ dwr.engine.setActiveReverseAjax(true); //必须配置 dwr.engine.setNotifyServerOnPageUnload( true);//必须配置 var code =randomString(6); //调用随机数生成方法,生成唯一的标识 ProtocolDwrUtils.onPageLoad(code); //精确推送,通过唯一的code alert("初始化Dwr。。。 。。。 。。。,随机编码为:"+code); } function helloWord() { alert("HelloWord !") } </script> <script type="application/javascript"> initDwr() </script> 欢迎使用DWR做测试 </body> </html>
6.手写controller测试
//测试,调用jsp页面,在jsp页面中通过js方法调用后台java方法 @RequestMapping(value = "test") public String test( Model model) { return "modules/task/dwrtest/dwrTest"; } //测试,调DWR,根据userId向不同的人推送消息 @RequestMapping(value = "dwr") public void dwr(String userId) { ProtocolDwrUtils utils = new ProtocolDwrUtils(); utils.sendProtocolToPage("",userId); }