---
title: "dwr comet 方式 实现不用前台请求，后台直接精确推送消息"
author: "wicketUser"
date: "2012-08-17T14:35:13Z"
tags: []
categories: ["Web前端"]
slug: "dwr-comet"
draft: false
lastmod: "2012-08-22T15:40:00Z"
id: 1635040
url: "https://wicketuser.iteye.com/blog/1635040"
---

突然发现我出书的可能性太小了，写了几篇小博文直接就是代码，没有啥文字修饰，好吧，

   综合从网上看的资料，得出以下总结。

 

    **step.1** 首先下载   [dwr.jar](http://dl.iteye.com/topics/download/bb2c6db5-3814-3833-921e-050c8f712980 "下载") 并在 web.xml 中 整合 DWR 及添加用户登入、登出监听器

   

 

&lt;servlet&gt;

                         &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;

                         &lt;servlet-class&gt;

                                         org.directwebremoting.servlet.DwrServlet

                         &lt;/servlet-class&gt;

                         &lt;init-param&gt;

                                         &lt;param-name&gt;debug&lt;/param-name&gt;

                                         &lt;param-value&gt;true&lt;/param-value&gt;

                         &lt;/init-param&gt;

                         &lt;init-param&gt;

                                         &lt;param-name&gt;activeReverseAjaxEnabled&lt;/param-name&gt;

                                         &lt;param-value&gt;true&lt;/param-value&gt;

                         &lt;/init-param&gt;

                         &lt;init-param&gt;

                                         &lt;param-name&gt;pollAndCometEnabled&lt;/param-name&gt;

                                         &lt;param-value&gt;true&lt;/param-value&gt;

                         &lt;/init-param&gt;

                         &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;

          &lt;/servlet&gt;

 

          &lt;servlet-mapping&gt;

                         &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;

                         &lt;url-pattern&gt;/dwr/\*&lt;/url-pattern&gt;

          &lt;/servlet-mapping&gt;

 

          &lt;!-- 用户登入、登出监听器 --&gt;

          **&lt;servlet&gt;**

                         **&lt;servlet-name&gt;initScriptSessionListener&lt;/servlet-name&gt;**

                         **&lt;servlet-class&gt;**

                                         **com.success.platform.component.messages.init.InitScriptSession**

                         **&lt;/servlet-class&gt;**

                         **&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;**

          **&lt;/servlet&gt;**

 step.2

 

·         建立 dwr.xml

 

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://www.getahead.ltd.uk/dwr/dwr30.dtd"&gt;

&lt;dwr&gt;

          &lt;allow&gt;

                         &lt;create creator="spring" javascript="DwrHelper"&gt;

                                         &lt;param name="beanName" value="messageHelper" /&gt;

                         &lt;/create&gt;

                        

          &lt;/allow&gt;

&lt;/dwr&gt;

 

1.     javascript="DwrHelper"                                      web 页内引用的 JS 文件名 .

2.     name="beanName" value="messageHelper"            spring 中 beanName

  step.3

  

·        建立 InitScriptSession.java

·        用户登入、登出监听器

 

public class InitScriptSession extends GenericServlet {

         

          /\**

            *

            \*/

          private static final long serialVersionUID = 1L;

 

          private static final Logger logger = Logger.getLogger(InitScriptSession.class);

 

          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) {

                                                       

                                                        try {

                                                                       HttpSession session = WebContextFactory.get().getSession();

                                                                      

                                                                       ScriptSession scriptSession = ev.getSession();

                                                                      

                                                                       String userId = session.getAttribute("userId").toString();

                                                                      

                                                                       scriptSession.setAttribute("userId", userId);

                                                                      

                                                                       logger.info("add " + scriptSession.getId()+ ", put userid into scriptSession");

                                                        } catch (Exception e) {

                                                                       logger.warn(" 会话失效 ");

                                                        }

                                         }

 

                                         public void sessionDestroyed(ScriptSessionEvent ev) {

                                                        ev.getSession().removeAttribute("userId");

                                                        logger.info("destroy ScriptSession: " + ev.getSession().getId());

                                         }

                         };

                        

                         manager.addScriptSessionListener(listener);

          }

 

          public void service(ServletRequest req, ServletResponse res) {

                        

                                         init();

          }

}

 

step.4

·      MessageEvent.java

·      消息监听

public class MessageEvent extends ApplicationEvent {

         

          /\**

            *

            \*/

          private static final long serialVersionUID = 9103980818480475235L;

 

          public MessageEvent(Object source) {

                         super(source);

          }

}

 

 

step.5

·      Message.java 消息实体

public class Message {

         

          private String receiverId;// 接收人

          private String sender;    // 发送人

          private String content;    // 内容

          private Date sendTime;     // 发送时间

         

         

         

         

          public Message(String receiverId, String sender, String content) {

                         super();

                         this.receiverId = receiverId;

                         this.sender = sender;

                         this.content = content;

          }

          public String getSendTime() {

                         String sdate="";

                         try {

                                         if(null == sendTime)sendTime=DateUtil.currentDate();

                                         sdate=DateUtil.dateToSting(sendTime);

                         } catch (Exception e) {

                                          

                         }

                         return sdate;

          }

          public void setSendTime(Date sendTime) {

                         this.sendTime = sendTime;

          }

          public String getReceiverId() {

                         return receiverId;

          }

          public void setReceiverId(String receiverId) {

                         this.receiverId = receiverId;

          }

          public String getSender() {

                         return sender;

          }

          public void setSender(String sender) {

                         this.sender = sender;

          }

          public String getContent() {

                         return content;

          }

          public void setContent(String content) {

                         this.content = content;

          }

         

         

}

 

step.6

 

MessageHelper.java 消息助手

 

@Service("messageHelper")  // 要和 dwr.xml 的 beanName 保持一致

@Scope("singleton")

public class MessageHelper implements ApplicationContextAware {

 

          private static ApplicationContext applicationContext;

 

          public void setApplicationContext(ApplicationContext ctx) {

                         MessageHelper.applicationContext = ctx;

          }

         

          public static void sendMessage(Message mes){

                        

                         if(applicationContext != null){

                                         applicationContext.publishEvent(new MessageEvent(mes));

                                        

                         }

          }

 

}

 

 

 

step.7

 

- NotifyClient.java  消息监听器

 

```
package com.success.platform.component.messages;

import java.util.Collection;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import com.success.platform.util.WebConfig;

@Service
public class NotifyClient implements ApplicationListener<MessageEvent> {
	
	public void onApplicationEvent(MessageEvent event) {
		if (event instanceof MessageEvent) {
			send((Message) event.getSource());
		}
	}

	private void send(final Message msg) {
		
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			
			public boolean match(ScriptSession session) {
				 
				if (session.getAttribute("UserId") == null)
					return false;
				else 
					return (session.getAttribute("UserId"
)).equals(msg.getReceiverId());
			}
		}, new Runnable() {
			public void run() {
				Collection<ScriptSession> colls = Browser.getTargetSessions();
				for (ScriptSession scriptSession : colls) {
					scriptSession.addScript(initFunctionCall("showMessage",  msg.getContent(),msg.getSender(),msg.getSendTime()));
				}
			}
		});
	}
	
	private ScriptBuffer initFunctionCall(String funcName, Object... params) {
		ScriptBuffer script = new ScriptBuffer();
		script.appendCall(funcName, params);
		return script;
	}
}
```

 

 

 

 

step.8

 

- index.jsp
- 这个页面，最好是个frameset 的主页面

 

&lt;%@ page contentType="text/html; charset=UTF-8"%&gt; &lt;%@taglib prefix="s" uri="/struts-tags"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=GB18030"&gt; &lt;title&gt;DWR's HelloWorld&lt;/title&gt; &lt;script type='text/javascript' src='${path}/dwr/engine.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='${path}/dwr/util.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='${path}/scripts/common/MessageHelper.js'&gt;&lt;/script&gt; &lt;script type='text/javascript'&gt; window.onload=activeReverseAjax; function activeReverseAjax(){ dwr.engine.setActiveReverseAjax(true); dwr.engine.setNotifyServerOnPageUnload(true);//页面销毁或刷新时销毁当前ScriptSession dwr.engine.setErrorHandler(null); } function showMessage(content,sender,sendtime) { $.messager.show({ title:sender + ' ' +sendtime, msg:content, timeout:0, showType:'slide' }); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt;

 

```

```

 

step.9

 

测试的话，可在 运行后台 servie 调用

 

MessageHelper.sendMessage(new Message("消息发送人的ID，对应Session内的userId","系统消息", "你好 触摸不到的狂野 怎么样收到信息了吗？。" ));

 

```

```