网上找到不少相关例子,不过大部分是dwr2的例子,效果一般,研究了一下dwr3.0相关内容,做了个DEMO,实现了向一个或多个精确目标推送内容。
重点在于向ScriptSessionManager中加入ScriptSessionListener监听ScriptSession的创建和销毁。
ScriptSessionListener中有2个需要实现的方法sessionCreated和sessionDestroyed,分别对应ScriptSession的创建和销毁,可以在方法中加入需要的内容。
我是在web.xml中配置了一个启动自动运行的servlet,用来添加监听。
InitScriptSession.java
- import javax.servlet.GenericServlet;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpSession;
- import org.directwebremoting.Container;
- import org.directwebremoting.ScriptSession;
- import org.directwebremoting.ServerContextFactory;
- import org.directwebremoting.WebContextFactory;
- import org.directwebremoting.event.ScriptSessionEvent;
- import org.directwebremoting.event.ScriptSessionListener;
- import org.directwebremoting.extend.ScriptSessionManager;
- public class InitScriptSession extends GenericServlet {
- ServletContext application;
- public void init() {
- Container container = ServerContextFactory.get().getContainer();
- ScriptSessionManager manager = container
- .getBean(ScriptSessionManager.class);
- ScriptSessionListener listener = new ScriptSessionListener() {
- public void sessionCreated(ScriptSessionEvent ev) {
- HttpSession session = WebContextFactory.get().getSession();
- ScriptSession scriptSession = ev.getSession();
- String userId = session.getAttribute("userId").toString();
- scriptSession.setAttribute("userId", userId);
- System.err.println("创建---"+scriptSession.getId()+"------- put userId into scriptSession as "
- + userId);
- }
- public void sessionDestroyed(ScriptSessionEvent ev) {
- System.out.println("销毁-----"+ev.getSession().getId());
- }
- };
- manager.addScriptSessionListener(listener);
- }
- public void service(ServletRequest req, ServletResponse res) {
- init();
- }
- }
在sessionCreated方法中把当前登陆人ID标识放入ScriptSession中,后面的推送过程中通过该标识判断推送目标。
推送方法:
- /**
- * 推给指定用户
- * @param userid
- * @param request
- * @return
- */
- private void send(final String receiverid, final String msg) {
- Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
- public boolean match(ScriptSession session) {
- if (session.getAttribute("userId") == null)
- return false;
- else
- return (session.getAttribute("userId")).equals(receiverid);
- }
- }, new Runnable() {
- public void run() {
- Collection<ScriptSession> colls = Browser.getTargetSessions();
- for (ScriptSession scriptSession : colls) {
- scriptSession.addScript(initFunctionCall(
- "dwr.util.setValue", "info", msg));
- }
- }
- });
- }
其他方法与网上查到的基本大同小异,有需要的朋友可以去网上down下来研究下。
重点关于解决页面每刷新一次会多创建一个新的ScriptSession的解决方法
由于ScriptSession的创建机制不同于HttpSession,它会在每次页面刷新的时候都会重新创建,而销毁机制却是失去连接或者失效之后一定时间才会自动销毁,这样就可能造成服务端可能就保存了很多的无用的ScriptSession,所以不仅仅会影响性能问题,更重要的是,可能就不能实现你想要的功能。
解决方法是在接收消息的页面,也就是你调用dwr.engine.setActiveReverseAjax(true);的页面调用一个dwr的方法。
dwr.engine.setNotifyServerOnPageUnload(true);
这个方法的功能就是在销毁或刷新页面时销毁当前ScriptSession,这样就保证了服务端获取的ScriptSession集合中没有无效的ScriptSession对象。