DWR实现服务器端向客户端推送消息

前端之家收集整理的这篇文章主要介绍了DWR实现服务器端向客户端推送消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.简介

DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。

它包含两个主要的部分:允许 JavaScriptWEB服务器上一个遵循了 AJAX原则的 Servlet获取数据.另外一方面一个JavaScript库可以帮助 网站开发人员轻松地利用获取的数据来动态改变网页的内容.
DWR采取了一个类似AJAX的新方法来动态生成基于JAVA类的JavaScript代码。这样WEB开发人员就可以在JavaScript里使用Java代码,就像它们是 浏览器本地代码( 客户端代码)一样;但是Java代码运行在WEB服务器端而且可以自由访问WEB 服务器的资源。出于安全的理由,WEB开发者必须适当地配置哪些Java类可以安全的被外部使用。 [1]
这个从JAVA到JavaScript的远程功能方法给DWR的用户带来非常像传统的RPC机制,就像RMI或者SOAP一样,而且拥有运行在WEB上但是不需要 浏览器插件的好处.
DWR不认为浏览器/WEB服务器协议是重要的,而更乐于保证 编程界面的简单自然.对此最大的挑战就是把AJAX的异步特性和正常JAVA方法调用的同步特性相结合.在异步模式下,结果数据在开始调用之后的一段时间之后才可以被异步访问获取到.DWR允许WEB开发人员传递一个 回调函数,来 异步处理Java 函数调用过程.
以上是百度百科中copy的废话,下面来看步骤

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,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>

:index.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 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>

clientPush.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>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存在覆盖的问题

猜你在找的Ajax相关文章