DWR第三篇之逆向Ajax升级

时间:2022-05-10 00:39:04

1. 本示例在第二篇架构基础上添加代码

2.在client.jsp开头的地方添加如下代码:

本示例需要做的是定向推送,那么就需要浏览器进行登录,从而进行定向的推送功能,为了节省时间,这里不做登录模块了,在url后拼接一个参数作为登录标识。

 <%
String id = request.getParameter("id");
session.setAttribute("id", id);
%>

这样,在登录的时候在url后边拼接id=xxx,就可以模拟登录功能,并将登陆信息存在session中。

3. 此外,client.jsp中还要添加如下代码(修改原来的地方)

 <script type="text/javascript">
window.onload = function() {
//开启逆向Ajax功能
dwr.engine.setActiveReverseAjax(true);
//开启关闭页面提醒服务器功能
dwr.engine.setNotifyServerOnPageUnload(true);
//对当前用户进行注册
CoreServlet.regist();
}
</script>

4. 修改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();">
<br>
发送目标:<input type="text" id="target">
发送内容:<input type="text" id="msg">
<input type="button" value="发送" onclick="directionalSendMsg();">
</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);
}
function directionalSendMsg() {
var target = dwr.util.getValue("target");
var msg = dwr.util.getValue("msg");
CoreServlet.directionalSendMsg(target + ":" + msg);
}
</script>
</html>

5. 在CoreServlet.java里添加两个方法

 /**
* 定向推送消息
*/
public void directionalSendMsg(String msg) {
final String[] param = msg.split(":");
Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
@Override
public boolean match(ScriptSession session) {
boolean flag = param[0].equals(session.getAttribute("key"));
return flag;
}
}, new Runnable() {
@Override
public void run() {
Util.setValue("msg", param[1]);
}
});
} /**
* 用户注册
*/
public void regist() {
// 获取当前的scriptSession
ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
// 获取HttpSession 并获得其中的userId
HttpSession session = WebContextFactory.get().getSession();
String id = (String) session.getAttribute("id");
// 对当前scriptSession的key设置指定的值
scriptSession.setAttribute("key", id);
}

6. 开三个窗口进行测试:

http://localhost:8080/dwr_demo/client.jsp?id=zhangsan
http://localhost:8080/dwr_demo/client.jsp?id=lisi
http://localhost:8080/dwr_demo/