dwr实现消息精准推送

关于dwr具体概念本文不做赘述,只谈实现。在参考了好几篇网上的博文后,把dwr整合到我的项目里面了,跑起来也没有问题。java推送有许多实现方式,诸如comet4j,websocket等等,还有一些收费的比如goeasy等,有兴趣朋友可以看看,废话不多说开始实现。

一:项目的应用场景

在项目里面有一个审批流程,上级领导把一个线索分配给下级实现,中途还可以变更下级,这样一来就会出现原来的下级正在对线索进行操作,而该线索已经不属于他,这时候我们需要一个消息实时推送给原来的下级,告诉他线索不属于你你甭干了,乖乖去玩吧!

二:实现

1:maven项目引入jar包,非maven项目去dwr官网下载

<dependency>
   <groupId>org.directwebremoting</groupId>
   <artifactId>dwr</artifactId>
   <version>3.0.2-RELEASE</version>
</dependency>

2:在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>  
		  <init-param>  
		    <param-name>crossDomainSessionSecurity</param-name>  
		    <param-value>false</param-value>  
		  </init-param>  
		  <init-param>  
		    <param-name>allowScriptTagRemoting</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>  

3:编写一个java类,用于要通知的页面把用户id传入保存session,这样服务端才能知道给谁发

public class MessagePush {

	public void onPageLoad(String userId) {  
		  
        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();  
  
        scriptSession.setAttribute("userId", userId); //把前台传入的id保存 
  
        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();  
  
        try {  
  
            dwrScriptSessionManagerUtil.init();  
  
        } catch (ServletException e) {  
  
            e.printStackTrace();  
  
        }  
  
    }  
}

还需要一个DwrScriptSessionManagerUtil工具类

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.directwebremoting.Container;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;
import org.directwebremoting.servlet.DwrServlet;

/**
 * @author Administrator
 *
 */

public class DwrScriptSessionManagerUtil extends DwrServlet{

	 public void init() throws ServletException {  
		  
	        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();  
	  
	                String userId = (String) session.getAttribute("userId");  
	  
	                System.out.println(">>>>>>>>>a ScriptSession is created!");  
	  
	                ev.getSession().setAttribute("userId", userId);  
	  
	            }  
	  
	            public void sessionDestroyed(ScriptSessionEvent ev) {  
	  
	                System.out.println(">>>>>>>>a ScriptSession is distroyed");  
	  
	            }  
	  
	        };  
	  
	        manager.addScriptSessionListener(listener);  
	  
	    }  
}

4:在与web.xml同级的目录下新建一个dwr.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE dwr PUBLIC  
    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"  
    "http://directwebremoting.org/schema/dwr30.dtd">  
<dwr>  
    <allow>  
        <create javascript="MessagePush" creator="new">  
            <param name="class" value="com.gtcity.web.util.MessagePush"></param>  
        </create>  
    </allow>  
</dwr> 

value="com.gtcity.web.util.MessagePush"代表对应的java类,javascript="MessagePush"代表页面引用的js名称,dwr目的就是要让js调用java方法


5:需要通知的页面

<script type="text/javascript" src="${pageContext.request.contextPath }/dwr/engine.js"></script>   
<script type="text/javascript" src="${pageContext.request.contextPath }/dwr/util.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/dwr/interface/MessagePush.js"></script>
这几个写法就是写死的,就是第三个*.js需要对应你在第4步上javascript="MessagePush"里面定义的名字

<body style="overflow-x:hidden;" οnlοad="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);onPageLoad();">

这几个也是必须的

function onPageLoad(){
        	 var userId = '${user.userId}';
             MessagePush.onPageLoad(userId);
         }
        
         //推送信息  
 function showMessage(autoMessage){  
                
             alert(autoMessage);
                
        }  

6:具体写消息推送的类,结合自身项目情景,我这里是在上级更改了下级后写的


A:给一个人发

//修改成功给张三发消息
		final String userId = "2";  //这个我写死张三userId=2
	        final String autoMessage = "上级已经更改了这条线索的归属人了!";  
	        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {  
	            public boolean match(ScriptSession session){  //验证符合条件的发送人
	                if (session.getAttribute("userId") == null){  
	                    return false;  
	                }else  {
	                    return (session.getAttribute("userId")).equals(userId);  
	                }
	            }  
	        }, new Runnable(){  
	              
	            private ScriptBuffer script = new ScriptBuffer();  
	              
	            public void run(){  
	                  
	                script.appendCall("showMessage", autoMessage);  
	                  
	                Collection<ScriptSession> sessions = Browser  
	  
	                .getTargetSessions();  
	                  
	                for (ScriptSession scriptSession : sessions){  
	                    scriptSession.addScript(script);  
	                }  
	            }  
	        });  

B:给多个人

//修改成功给张三,李四发消息
		final String userId = "2,3,***";  
	        final String autoMessage = "上级已经更改了这条线索的归属人了!";  
	        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {  
	            public boolean match(ScriptSession session){  
	                if (session.getAttribute("userId") == null){  
	                    return false;  
	                }else  {
	                	String attribute = (String) session.getAttribute("userId");
	                	return (userId.contains(attribute));
	                  
	                }
	            }  
	        }, new Runnable(){  
	              
	            private ScriptBuffer script = new ScriptBuffer();  
	              
	            public void run(){  
	                  
	                script.appendCall("showMessage", autoMessage);  
	                  
	                Collection<ScriptSession> sessions = Browser  
	  
	                .getTargetSessions();  
	                  
	                for (ScriptSession scriptSession : sessions){  
	                    scriptSession.addScript(script);  
	                }  
	            }  
	        });  

至此,dwr精准推送完毕。如果还想进一步结合spring有兴趣可以看看这篇文章 springMVC+dwr3 实现精确推送信息(2种方法)



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值