SSH项目中使用DWR框架实现即时精确消息推送

本来自己想写的但是写了几句,发现语言组织能力有限。我还是在这篇文章基础上作写我的东西吧

实现项目需求及方法
    目的:当数据操作发生某种异常时向相应的用户发送即时消息。例如:xx文件处理有N条数据是垃圾数据。
    实现:
          当数据有相应异常时,向数据库插入一条数据,并向指定用户(没有指定用户就不推送)推送消息;
          前台页面监控,每个用户登录或每刷新此页面一次都调用后台程序并把用户编码传至后台存入ScriptSession,并判断当前用户有无消息,有消息立马推送;
          前台该页面长连接实现接收推送信息脚本并执行。
一、需要文件:1、dwr.xml(与web.xml放在同一目录下) 2、engine.js  util.js (引入相应的接受或发送页面)3、dwr.jar 将它放在你webapp的WEB-INF/lib目录下。

二、编辑配置文件
      1、web.xml加入 如下:
        <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>
            <description>使用服务器推技术(反转AJAX)</description>
            <param-name>activeReverseAjaxEnabled</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>initApplicationScopeCreatorsAtStartup</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>maxWaitAfterWrite</param-name>
            <param-value>100</param-value>
        </init-param>
        <load-on-startup>4</load-on-startup>
    </servlet>
     
      <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>


   注意,要把<servlet>和其他<servlet>放在一起,<servlet-mapping>要和其他<servlet-mapping>放在一起!!

    2、dwr.xml 在web.xml的同一目录下,创建dwr.xml,并且将要被调用的java类写入其中。

<?xml version="1.0" encoding="UTF-8"?>
<dwr>
	<allow>
	    <create creator="spring" javascript="Remote"> 
        <param name="beanName" value="remote" /> 
        <include method="noticeNewOrder" /> 
        <include method="getData" /> 
         <include method="putMessger" /> 
         </create>
	</allow>
</dwr>



applicationContext.xml中加入<bean id="remote" class="包名.Remote"></bean>



三、编写被调用的java类  
   注:UserMng  和OrderMng 业务的具体类,被Spring管理 这里不做重点。
       有关UserMng  和OrderMng的代码不用了解,知道是一部操作即可,与实现发送信息无直接的关系。
    
 
package com.yds.common;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.yds.sym.entity.User;
import com.yds.sym.service.UserMng;
import com.yds.taskoder.service.OrderMng;
   public class Remote{
	@Autowired
	UserMng umng;
	@Autowired
	OrderMng oMng;
	//负责将当前用id户存入ScriptSession,并判断当前用户是否要推送消息
    public void getData(String userCode) {
    	int con=0;//当前用户或者需推送用户待处理任务条数
    	try {
            WebContext wctx = WebContextFactory.get();
            //得到当前页面的session
            ScriptSession scriptSession = wctx.getScriptSession();
            
            User user=umng.findById(Integer.parseInt(userCode));//当前用户信息(写自己代码)
            Integer a=oMng.loadUserTask(user);//当前用户消息数
            con= a==null?0:a;
          //设置session属性值 用户code
            scriptSession.setAttribute("usercode", user.getId());
    		ScriptBuffer script = new ScriptBuffer();
    		if(con>0){
            	script.appendScript("InitMsgBox(").appendData(user.getRealName()).appendScript("," + con + ");");
            	//像当前访问页面的用户推送消息
            	scriptSession.addScript(script);
    		}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    //负责推送消息
    public void putMessger(String departementid){
    	int con=0;//当前用户或者需推送用户待处理任务条数
    	try {
    		Integer a=oMng.countOfOrders(Integer.parseInt(departementid));
    		con= a==null?0:a+1;
    		Map<Integer, Integer> map=new HashMap<Integer, Integer>();//存放需要推送的用户id
    		List<User> list=umng.findUserBydpId(Integer.parseInt(departementid));//获取需要推送的所有用户
    		for (int i = 0; i < list.size(); i++) {
    			User u=list.get(i);
    			map.put(u.getId(), u.getId());
    		}
    		if(!map.isEmpty()){
    			this.noticeNewOrder(con,map);
    		}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    // 得到推送信息并推送
    public void noticeNewOrder(int con,Map<Integer, Integer> umap) {
        WebContext wctx = WebContextFactory.get();
        ScriptBuffer script = new ScriptBuffer();
        //指定的页面(可以是动态的哟。。。我这个地址指向的是目标页面)
        String currentPage = "/sycj/login/symSubmit.action";
        //得到登录此页面的scriptSession的集合
        Collection<ScriptSession> pages = wctx.getScriptSessionsByPage(currentPage);
        for (ScriptSession session: pages) {
            if(session.getAttribute("usercode")!=null){
            	Integer userinfo=(Integer)session.getAttribute("usercode");
            	//判定目标用户推信息
	            if(umap.containsValue(userinfo)){
	            	User user=umng.findById(userinfo);
	            	script.appendScript("InitMsgBox(").appendData(user.getRealName()).appendScript("," + con + ");");
	                session.addScript(script);
	            }
            }
           
        }
    }
}


四、测试dwr

  将代码放入应用服务器(比如Tomcat),启动。
  然后在地址栏输入http://localhost:8080/你的工程/dwr
  然后点击Remote   可以看见它的两个方法getData(),noticeNewOrder() ,putMessger()说明dwr已配置成功!

五、编写jsp 和 消息框js

  1、消息框activeReverseAjax.js 代码如下:
//消息框初始化
function InitMsgBox(fileName, mun) {
    var messageBox = document.getElementById("myMessageBox");
    messageBox.style.width = 180;
    messageBox.style.height = 110;
    messageBox.style.border = "solid black 1px";
    messageBox.style.position = "absolute";
    messageBox.style.right = 0;
    messageBox.style.bottom = 0;
    messageBox.style.display = "none";

    var titleContent = "";// 消息框内容
    var CSStext = "margin:1px;color:black; border:2px outset;background-color:buttonface;width:16px;height:14px;font-size:12px;line-height:11px;cursor:hand;";

    titleContent = titleContent
            + "<table width=100% height=100% cellpadding=0 cellspacing=0 border=0 >";
    titleContent = titleContent
            + "<tr style=';font-size:12px;background:#0099CC;height:20px;cursor:default'>";
    titleContent = titleContent
            + "<td style='color:white;padding-left:5px'>消息提示</td>";
    titleContent = titleContent
            + "<td style='color:#ffffff;padding-right:5px;' align=right>";
    titleContent = titleContent
            + "<span id=Close οnclick='pophide()' style='" + CSStext
            + "font-family:System;padding-right:2px;' title='关闭'>x</span>";
    titleContent = titleContent + "</td></tr><tr><td colspan=2>";
    titleContent = titleContent
            + "<div id=include style='overflow:scroll;overflow-x:hidden;overflow-y:auto;HEIGHT:100%;padding-left:5px;padding-top:3px;font-size:12px;'>";
    titleContent = titleContent + "您好!"+fileName ;
    titleContent = titleContent + ",有" + mun + "条任务单等待您处理,";
    titleContent = titleContent + "请及时处理!<br>";
    titleContent = titleContent + "<br><br><br><br>";
    titleContent = titleContent + "</div>";
    titleContent = titleContent + "</td></tr></table>";
    messageBox.innerHTML = titleContent;
    // 消息框弹出方法
    $("#myMessageBox").slideDown(1000);
}

// 消息框关闭方法
function pophide() {
    $('#myMessageBox').slideUp(1000);
}
function updatePollStatus(pollStatus) {
    dwr.util.setValue("pollStatus", pollStatus ? "Online" : "Offline", {escapeHtml:false});
}

// 页面body onload方法
function tempOnLoad() {
    dwr.engine.setActiveReverseAjax(true);
}



2、监控发送页面 在webapp目录下不做介绍重点。

   注意:引入Remote.js、engine.js、util.js路径以测试页面上的路径为准。
        <script type='text/javascript' src="<%=request.getContextPath()%>/dwr/interface/Remote.js"></script>
        <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()%>/js/dwr/activeReverseAjax.js"></script>
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">
            var path="<%=request.getContextPath()%>";
            $(function(){
                 var code=$('#usercode').val();//这里是你传入的参数,可以是直接写自己的值
                 Remote.getData(code);//调用后台程序
            })
           
        </script>
你的目标页面必须要有<div id="myMessageBox"></div>这是消息框,



当你在页面进行了操作需要向指定用户发送消息时调用这个js Remote.putMessger(自己的值)函数,后台判断推送的目标用户




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值