2. 首先修改web.xml里dwr的servlet配置:
<!-- 配置dwr请求的servlet -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>activeReverseAjaxEnabled</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>
3. 在CoreServlet.java里添加推送消息的方法
public void send(final String msg) {
// 将接收到的内容推送到所有的浏览器
Browser.withAllSessions(new Runnable() {
@Override
public void run() {
Util.setValue("msg", msg);
}
});
}
4. 新建client.jsp用于接受服务器推送的请求
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>dwr_demo</title>
<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/CoreServlet.js'></script>
</head>
<body>
<h1>服务器推送的内容</h1>
<span id="msg"></span>
</body>
<script type="text/javascript">
window.onload = function() {
//开启逆向Ajax功能
dwr.engine.setActiveReverseAjax(true);
}
</script>
</html>
5. 修改index.jsp为:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>dwr_demo</title>
<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/CoreServlet.js'></script>
</head>
<body>
<input type="button" value="发送" onclick="sayHello();">
<br>
<input type="text" id="getHello">
<input type="button" value="发送" onclick="getHello();">
<input type="text" id="getHelloValue">
<br>
<input type="text" id="sendMsg">
<input type="button" value="推送" onclick="sendMsg();">
</body>
<script type="text/javascript">
function sayHello() {
CoreServlet.sayHello();
}
function getHello() {
var name = dwr.util.getValue("getHello");
CoreServlet.getHello(name, function(data) {
dwr.util.setValue("getHelloValue", data);
});
}
function sendMsg() {
var msg = dwr.util.getValue("sendMsg");
CoreServlet.send(msg);
}
</script>
</html>
6. 测试(注意,需要JDK1.7及以上)