JSP学习笔记(九十六):学习使用dwr 中的push技术
dwr里面的push技术可以做这样的事情:服务器发送一个广播,让每一个客户端都能接收到这个广播。一般的做法,就是让客户端每隔一定时间刷新一下,获取服务器发送的请求,这种方法可以,不过性能一定是最低的。dwr的push技术是让服务器每次发送广播时,把这个广播推送给客户端,不用客户端去刷新,据说是dwr的推送是基于长连接的,性能不错,具体的原理,我暂时也没搞清楚,先不管这些了,先实现了再说。
上一篇文章已经介绍了dwr的使用,这里我假设你已经会用dwr的基本使用了。
修改web.xml,启用dwr的Reverse Ajax,也就是我们要用的push技术:
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
添加一个Servlet,用来发送广播:
public class TestServlet extends HttpServlet {
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServerContext wctx = ServerContextFactory.get(getServletContext());
Collection<ScriptSession> sessions = wctx.getAllScriptSessions();
// Collection<ScriptSession> sessions =
// wctx.getScriptSessionsByPage("/poject/test.html");
String msg = request.getParameter("msg");
if(msg==null)
{
msg = "empty";
}
ScriptBuffer script = new ScriptBuffer();
script.appendScript("showMessage(").appendData(msg)
.appendScript(");");
for (ScriptSession session : sessions) {
session.addScript(script);
}
}
}
添加一个html页面,用来接收服务端广播:
<script type="text/javascript">
dwr.engine.setActiveReverseAjax(true);
function showMessage(msg)
{
alert(msg);
}
</script>