DWR入门

© 版权声明:本文为博主原创文章,转载请注明出处


1. 作用

  • 可以动态生成基于JAVA类的JavaScript代码,使得可以使用JavaScript调用JAVA方法
  • 可以进行内容推送,将指定内容推送给某个人或某些人(需要页面进行触发

2. 实现

2.1 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>org.dwr</groupId>
	<artifactId>DwrDemo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- dwr -->
		<dependency>
		    <groupId>org.directwebremoting</groupId>
		    <artifactId>dwr</artifactId>
		    <version>3.0.2-RELEASE</version>
		</dependency>
		<!-- commons-logging -->
		<dependency>
		    <groupId>commons-logging</groupId>
		    <artifactId>commons-logging</artifactId>
		    <version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>DwrDemo</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<target>1.8</target>
					<source>1.8</source>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2.2 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" metadata-complete="true">
  
  	<servlet>
  		<servlet-name>dwr</servlet-name>
  		<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  		<init-param>
  			<param-name>activeReverseAjaxEnabled</param-name>
  			<param-value>true</param-value>
  			<description>使用服务器推技术(反转AJAX)</description>
  		</init-param>
  		<init-param>
  			<param-name>crossDomainSessionSecurity</param-name>
  			<param-value>false</param-value>
  			<description>使能够从其他域进行请求 true:开启 false:关闭</description>
  		</init-param>
  		<init-param>
  			<param-name>allowScriptTagRemoting</param-name>
  			<param-value>true</param-value>
  			<description>允许远程JS</description>
  		</init-param>
  		<init-param>
  			<param-name>debug</param-name>
  			<param-value>true</param-value>
  			<description>启动调试模式</description>
  		</init-param>
  	</servlet>
  	<servlet-mapping>
  		<servlet-name>dwr</servlet-name>
  		<url-pattern>/js/dwr/*</url-pattern>
  	</servlet-mapping>
  
</web-app>

2.3 java代码实现

java代码用两种方式实现
  • 使用以前的老方法,现在已经被标注为过时,但依旧可以使用。适合使用旧版本的人使用
  • 使用最新的方法,适合使用新版本的人使用

2.3.1 DwrPush.java

package org.dwr.util;

import java.util.Collection;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;

public class DwrPush {

	@SuppressWarnings("deprecation")
	public void send(String msg) {
		// 获取WebContext对象,获取request,session等的辅助类
		WebContext webContext = WebContextFactory.get();
		// 获取访问页面的所有用户
		Collection<ScriptSession> sessions = webContext.getAllScriptSessions();
		// 创建ScriptBuffer对象
		ScriptBuffer sb = new ScriptBuffer();
		// 调用old_callback方法,传入参数
		sb.appendCall("old_callback", msg);
		// 根据ScriptSession创建DWR的Util对象
		Util util = new Util(sessions);
		// 回调js方法
		util.addScript(sb);
	}
	
}

2.3.2 NewDwrPush.java

    package org.dwr.util;

import java.util.Collection;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;

public class NewDwrPush {
	
	public void send(String msg) {
		// 创建Runnable对象,设置回调对象以及回调方法
		Runnable runnable = new Runnable() {
			
			// 创建ScriptBuffer对象
			private ScriptBuffer script = new ScriptBuffer();
			
			@Override
			public void run() {
				// 设置要调用的js及参数
				script.appendCall("new_callback", msg);
				// 得到所有的ScriptSession对象
				Collection<ScriptSession> sessions = Browser.getTargetSessions();
				// 遍历每一个ScriptSession
				for (ScriptSession session: sessions) {
					session.addScript(script); // 将推送内容添加到ScriptSession中
				}
			}
		};
		
		// 执行推送
		Browser.withAllSessions(runnable);
	}
	
}

2.4 dwr.xml

  • dwr.xml默认必须放在WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
    "http://directwebremoting.org/schema/dwr30.dtd">
<dwr>
	<allow>
		<create creator="new" javascript="DwrPush">
			<param name="class" value="org.dwr.util.DwrPush"/>
		</create>
		
		<create creator="new" javascript="NewDwrPush">
			<param name="class" value="org.dwr.util.NewDwrPush"/>
		</create>
	</allow>
</dwr>

2.5 index.jsp

  • 页面里引入的js是由Dwr自动生成的,不用自己手动引入
  • engine.js和util.js路径是由配置在web.xml中的url-pattern去掉最前面的/加上名称。本例中指定的为/js/dwr/,则路径应为js/dwr/engine.jsjs/dwr/util.js*。
  • 自定义的js(js名称即为dwr.xml中create标签的javascript属性指定的)前缀跟engine.js等一样,不过要多加一层interface,本例即为js/dwr/interface/NewPush.js
  • engine.js和util.js需放在jquery.js之前
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Dwr 测试</title>
</head>
<body>
	<ul id="new_ul" style="color: red; font-size: 30px;">
		<li>新推送方式</li>
	</ul>
	
	<input type="text" name="new_msg" id="new_msg" size="30" style="height: 40px; font-size: 30px;"/>
	<input type="button" id="new_sign" value="新方式发布信息"/>
	
	<ul id="old_ul" style="color: red; font-size: 30px;">
		<li>旧推送方式</li>
	</ul>
	
	<input type="text" name="old_msg" id="old_msg" size="30" style="height: 40px; font-size: 30px;"/>
	<input type="button" id="old_sign" value="旧方式发布信息"/>
	
	
	<!-- 处理所有服务器通信 -->
	<script type="text/javascript" src="js/dwr/engine.js"></script>
	<!-- 帮助你用你从服务器得到的数据改变网页 -->
	<script type="text/javascript" src="js/dwr/util.js"></script>
	<script type="text/javascript" src="js/dwr/interface/DwrPush.js"></script>
	<script type="text/javascript" src="js/dwr/interface/NewDwrPush.js"></script>
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
	<script type="text/javascript">
	
		$(function() {
			
			// 启动该页面的Reverse Ajax功能
			dwr.engine.setActiveReverseAjax(true);
			
			// 调用旧推送方式
			$("#old_sign").click(function() {
				DwrPush.send($("#old_msg").val());
				
			});
			
			// 调用新推送方式
			$("#new_sign").click(function() {
				NewDwrPush.send($("#new_msg").val());
				
			});
			
		});
	
		// 旧方式推送回调函数
		function old_callback(msg) {
			$("#old_ul").html($("#old_ul").html() + "<br/>" + msg);
		}
		
		// 新方式推送回调函数
		function new_callback(msg) {
			$("#new_ul").html($("#new_ul").html() + "<br/>" + msg);
		}
	
	</script>
</body>
</html>

参考:
Dwr实现JAVA服务器端向客户端推送消息
更好的MarkDown体验:https://www.zybuluo.com/chy282/note/1012299


posted @ 2018-01-09 10:50  禁忌夜色153  阅读(307)  评论(0编辑  收藏  举报