Dwr的ScriptSessionListener使用,监听ScriptSessionListener的产生,消亡(2)
index.jsp
? <%
? //添加监听器
??? Container container = ServerContextFactory.get().getContainer();?
?ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);?
?manager.addScriptSessionListener(new AddScriptSessionListener());
? %>
<script type='text/javascript'?? src='<%=request.getContextPath()%>/dwr/engine.js'></script>
<script type='text/javascript'?? src='<%=request.getContextPath()%>/dwr/util.js'></script>
<script type='text/javascript'?? src='<%=request.getContextPath()%>/dwr/interface/UserService.js'></script>
<body onload="dwr.engine.setActiveReverseAjax(true);">
-------------------------------------------------------------------
AddScriptSessionListener.java
?
?package com.huawei.listener;
?
?import java.util.HashMap;
?import java.util.Map;
?
?import org.directwebremoting.ScriptSession;
?import org.directwebremoting.WebContext;
?import org.directwebremoting.WebContextFactory;
?import org.directwebremoting.event.ScriptSessionEvent;
?import org.directwebremoting.event.ScriptSessionListener;
?
?public class AddScriptSessionListener implements ScriptSessionListener {
? public static Map<String, ScriptSession> sc=new HashMap<String, ScriptSession>();
?
? public void sessionCreated(ScriptSessionEvent ev) {
?? WebContext webContext = WebContextFactory.get();
?? sc.put(webContext.getSession().getId(), ev.getSession());
?? System.out.println("add --------->"+ev.getSession().getId());
? }
?
? public void sessionDestroyed(ScriptSessionEvent ev) {
?? System.out.println("remove --------->"+ev.getSession().getId());
? }
?
?
?}
----------------------------------
UserService.java
?
public void addUser(){
??????? ScriptBuffer script = new ScriptBuffer();??
??????? script.appendScript("add(").appendData(System.currentTimeMillis())??
????????? .appendScript(");");??
??????? sc2=AddScriptSessionListener.sc;
??????? for (String str:sc2.keySet()) {
???????? System.err.println("-------"+sc2.get(str).getId());
???????? sc2.get(str).addScript(script);??
? }
?}
?
?
//如果服务器关闭dwr还弹错误提示窗口,在页面上加上这一句
?? dwr.engine.setErrorHandler(function(){});
?