使用DWR进行消息推送测试

DWR开发

  • DWR介绍

DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。

  • 为何使用到DWR

场景:当用户1添加一条信息,用户2对该条信息进行处理,当处理操作结束时,要及时提醒用户1该条数据已经被更新。

现在已经改为web socket了,文档是3年前编辑的,留存一下

  • DWR开发流程
  1. 首先在项目内加入DWR所需的包,pom.xml文件中添加


    org.directwebremoting

    dwr

    3.0.1-RELEASE

  1. 在与web.xml同级目录下新建dwr.xml,内容如下
xml version="1.0" encoding="UTF-8"?>

"-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"

        "http://getahead.org/dwr/dwr30.dtd">



          
                  

               creator="new" javascript="MessagePush">

                 name="class" value="com.centnet.cpi.util.MessagePush"/>

              
                   

                creator="new" javascript="TestPush">

                  name="class" value="com.centnet.cpi.util.TestPush"/>

              

          

  1. 被动推送消息一般在主页显示,所以初始化设置在home.html文件中引入所需js




说明:engine.js和util.js是dwr.jar包自带的,MessagePush是自动生成的一个动态的js。只需直接引入这些包。

4、在home.html中添加初始化代码

  1. 编写MessagePush.java
package com.centnet.cpi.util;

import org.directwebremoting.ScriptSession;

import org.directwebremoting.WebContextFactory;



import javax.servlet.ServletException;



/**

 * Created by wuml on 2016/7/19.

 */

public class MessagePush{

    

    public void onPageLoad(String userId) {

        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();

        scriptSession.setAttribute(userId, userId);

        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();

        try {

            dwrScriptSessionManagerUtil.init();

        } catch (ServletException e) {

            e.printStackTrace();

        }

    }

}
  1. MessagePush.java中设计到一个DwrScriptSessionManagerUtil 类,接下来编写DwrScriptSessionManagerUtil 类
package com.centnet.cpi.util;



import com.centnet.base.model.ShiroUser;

import org.apache.shiro.SecurityUtils;

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;



import javax.servlet.ServletException;

import javax.servlet.http.HttpSession;



public class DwrScriptSessionManagerUtil extends DwrServlet {



    private static final long serialVersionUID = -7504612622407420071L;

    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();

                ShiroUser principal = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

                String  userId = principal.getUserId().toString();

                System.out.println("a ScriptSession is created!"+userId);

                ev.getSession().setAttribute("userId", userId);

            }

            public void sessionDestroyed(ScriptSessionEvent ev) {

                System.out.println("a ScriptSession is distroyed");

            }

        };

        manager.addScriptSessionListener(listener);

    }

}
  1. 接下来是调用dwr消息推送的类,TestPush.java
package com.centnet.cpi.util;





import com.centnet.base.web.libs.controller.BaseController;

import org.directwebremoting.Browser;

import org.directwebremoting.ScriptBuffer;

import org.directwebremoting.ScriptSession;

import org.directwebremoting.ScriptSessionFilter;



import java.util.Collection;



public class TestPush extends BaseController{

    public void sendMessageAuto(String userid, String message,String type){



        final String userId = userid;

        final String autoMessage = message;

        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(){
                 /**appendCall()第一个参数为js中用来推送消息的函数,第二个以及后面的参数是函数中的参数例如
script.appendCall("showMessage", autoMessage,type);

代表js中的showMessage(autoMessage,type);
                 **/

                script.appendCall("showMessage", autoMessage,type);

                Collection sessions = Browser.getTargetSessions();

                for (ScriptSession scriptSession : sessions){

                    scriptSession.addScript(script);

                }

            }

        });

    }

} 
  1. 主动推送的页面引入js(如:添加操作,需要推送消息,在该html引入如下js)




  1. 对应添加操作的做推送消息(此处可以在后台直接调用也可以在js回调的时候调用)

后台调用:

TestPush testPush = new TestPush();
/**与TestPush中的sendMessageAuto对应**/

testPush.sendMessageAuto("被推送人的ID","推送的内容","");

前台js调用

 function test() {  

//id为被推送的人的ID

     var id= document.getElementById("userId").value;  

     TestPush.sendMessageAuto(id,"推送消息");  

  }  

  1. 给出showMessage方法的写法,写在home.html中
//推送信息  

function showMessage(autoMessage,type){

    $("#showMessageSpan").html(autoMessage);

    setTimeout(function () {

        showDiv();

    }, 1000)

    setTimeout(function () {

        hideDiv();

    }, 6000)

}
function showDiv()

{

    $("#showRealTime").slideDown("slow");

}

function hideDiv() {

    $("#showRealTime").slideUp("slow");

}
  1. 弹出框的div   写在home.html中




id="showRealTime" >         href="javaScript:void(0)" class="float:right" >系统提示:        
class="float:left;width:300px;height:50px;text-align:center">         style=" line-height:50px;" id="showMessageSpan">        

 

你可能感兴趣的:(spring)