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

: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存在覆蓋的問題


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章