1.简介
DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。
2.前提条件:
2.1 dwr.jar 此包可以到官网下载:http://directwebremoting.org/dwr/downloads/index.htm(必须)
2.2 commons-logging-xxxx.jar(官网说需要)
3.eclipse中new >> Dynamic Web Project 复制dwr.jar到lib目录下会自动build path
4.打开web.xml编辑:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>dwrDemo</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.yun.study.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> <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>
<!--此处必须要有 不然前端js不能自动引入--> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> </web-app>以上具体的 init-param可以到官网查查文档什么的搞定
5.在web.xml同级目录下新建一个文件 dwr.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> <dwr> <allow> <create creator="new" javascript="MessagePush"> <param name="class" value="com.yun.study.service.MessagePush" /> </create> <create creator="new" javascript="TestPush"> <param name="class" value="com.yun.study.service.Test" /> </create> </allow> </dwr>以上可以看出 我的class有两个
com.yun.study.service.MessagePush
com.yun.study.service.Test属性javascript的值表示是在js中用到该类的时候引用的名字
6.新建的java类如下:
bean:
package com.yun.study.model; public class User { private String userId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
package com.yun.study.servlet; 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; import com.yun.study.model.User; public class DwrScriptSessionManagerUtil extends DwrServlet { private static final long serialVersionUID = 109326676726848212L; public void init() throws ServletException { try { 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")) .getUserId() + ""; System.out.println("======>>>a ScriptSession is created,userId="+userId); ev.getSession().setAttribute("userId", userId); } public void sessionDestroyed(ScriptSessionEvent ev) { String userId = (String) ev.getSession().getAttribute("userId"); System.out.println("======>>>userId="+userId+" ScriptSession is distroyed"); } }; manager.addScriptSessionListener(listener); } catch (Exception e) { e.printStackTrace(); } } }
package com.yun.study.service; import javax.servlet.ServletException; import org.directwebremoting.ScriptSession; import org.directwebremoting.WebContextFactory; import com.yun.study.servlet.DwrScriptSessionManagerUtil; public class MessagePush { public void onPageLoad(String userId) { System.out.println("=====>>>>MessagePush onPageLoad invoke begin!"); ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); scriptSession.setAttribute("userId", userId); DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil(); try { dwrScriptSessionManagerUtil.init(); System.out.println("=====>>>>MessagePush onPageLoad invoke end!"); } catch (ServletException e) { e.printStackTrace(); } } }
package com.yun.study.service; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import org.directwebremoting.Browser; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import org.directwebremoting.ScriptSessionFilter; public class Test { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void sendMessageAuto(String userid) { System.out.println("======>>>sendMessageAuto invoke begin!"); final String userId = userid; final String sendMessage = "长江长江,我是黄河,收到请回答!当前时间是:"+sdf.format(new Date()); 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() { System.out.println("====>>>invoke client browser task run......."); script.appendCall("showMessage", sendMessage); Collection<ScriptSession> sessions = Browser.getTargetSessions(); for (ScriptSession scriptSession : sessions) { System.out.println("===>>>loop execute sessions userId:"+scriptSession.getAttribute("userId")); scriptSession.addScript(script); } } }); System.out.println("======>>>sendMessageAuto invoke end!"); } }
package com.yun.study.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.yun.study.model.User; /** * Servlet implementation class ServerPushMessageServlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageName = request.getParameter("pageName"); String sessionId = request.getSession().getId(); User u = new User(); u.setUserId(sessionId); request.getSession().setAttribute("userinfo", u); response.sendRedirect(pageName); } }
登录:login.jsp
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <base href="<%=basePath%>"></base> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>dwr test</title> </head> <body> <form action="<%=basePath%>/loginServlet" method="post"> <p>请点击以下button 将会模拟登录得到一个sessionKey设置到你的session中用于表示您的身份,</p> <p style="color: red;">界面将跳转到一个客户端页面(用于接收服务器推送消息的)!</p> <br/><input type="hidden" name="pageName" value="index.jsp"/> <input type="submit" value="跳转到客户端"/> </form> <br/><br/><br/> <hr/> <form action="<%=basePath%>/loginServlet" method="post"> <p>请点击以下button 将会模拟登录得到一个sessionKey设置到你的session中用于表示您的身份,</p> <p style="color: red;">界面将跳转到一个触发服务端推送消息的界面(用于通知服务器推送消息给客户端的)!</p><br/> <input type="hidden" name="pageName" value="clientPush.jsp"/> <input type="submit" value="跳转到通知服务发送界面"/> </form> </body> </html>
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <base href="<%=basePath%>"></base> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>dwr client test</title> <script type="text/javascript" src="<%=basePath%>/js/jquery-1.7.2.min.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="<%=basePath%>/dwr/interface/MessagePush.js"></script> <script type="text/javascript"> //通过该方法与后台交互,确保推送时能找到指定用户 function onPageLoad() { var userId = '${userinfo.userId}'; MessagePush.onPageLoad(userId); } //服务器向客户端推送信息的方法 function showMessage(autoMessage) { $("#serverSay").html(autoMessage); } </script> </head> <body onload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;"> This is my DWR DEOM page.please copy this userId <span style="color: red;">${userinfo.userId}</span> to clientPush.jsp page to trigger a event,server will send message to client...... <hr/><br/> <div id="DemoDiv">demo</div> <h2 style="color: red;" id="serverSay"></h2> </body> </html>
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <base href="<%=basePath%>"></base> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>server push message trigger</title> <script type="text/javascript" src="<%=basePath%>/js/jquery-1.7.2.min.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 userId = $("#userId").val(); TestPush.sendMessageAuto(userId); } </script> </head> <body> client userId <input type="text" name="userId" id="userId" /> <br /> <input type="button" value="Send" onclick="test()" /> </body> </html>
ok!
注意:以上测试 客户端和通知服务端的页面请使用两个不同的浏览器测试,以免session存在覆盖的问题
版权声明:本文为博主原创文章,未经博主允许不得转载。