`
wicketUser
  • 浏览: 15902 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

dwr comet 方式 实现不用前台请求,后台直接精确推送消息

    博客分类:
  • web
阅读更多

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

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

 

    step.1 首先下载   dwr.jar 并在 web.xml 整合 DWR 及添加用户登入、登出监听器

   

 

<servlet>

                         <servlet-name>dwr-invoker</servlet-name>

                         <servlet-class>

                                         org.directwebremoting.servlet.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>pollAndCometEnabled</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>

                         <servlet-name>initScriptSessionListener</servlet-name>

                         <servlet-class>

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

                         </servlet-class>

                         <load-on-startup>1</load-on-startup>

          </servlet>

 step.2

 

·         建立 dwr.xml

 

<?xml version="1.0" encoding="UTF-8"?>

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

<dwr>

          <allow>

                         <create creator="spring" javascript="DwrHelper">

                                         <param name="beanName" value="messageHelper" />

                         </create>

                        

          </allow>

</dwr>

 

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 的主页面

 

<%@ page contentType="text/html; charset=UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>DWR's HelloWorld</title> <script type='text/javascript' src='${path}/dwr/engine.js'></script> <script type='text/javascript' src='${path}/dwr/util.js'></script> <script type='text/javascript' src='${path}/scripts/common/MessageHelper.js'></script> <script type='text/javascript'> 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' }); } </script> </head> <body> </body> </html>

 


 

step.9

 

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

 

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

 


 

 

  • dwr.jar (1.1 MB)
  • 下载次数: 267
0
4
分享到:
评论
3 楼 zhan8863 2012-11-16  
你好,dwr comet的完整示例能否发我一份!谢谢 zhan8863@126.com
2 楼 liucan1818 2012-10-23  
《dwr comet 方式 实现不用前台请求,后台直接精确推送消息》你的这篇文章写的源代码还有吗? 我想看一下 就是做的ERP系统的一个及时的消息提醒功能。你有什么建议吗 。谢谢 。我的邮箱444373025@qq.com
1 楼 wicketUser 2012-08-17  
iteye 好大的BUG 发布后不能重新编辑啊。。。。全乱了。。。。。。

相关推荐

Global site tag (gtag.js) - Google Analytics