DWR 消息推送

DWR 消息推送

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <servlet-name>spring3</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/conf/spring3-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring3</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>spring3</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <description>字符集过滤器(前台往后台提交数据编码)</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <description>字符集编码</description>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

要显示推送消息的页面加上

<!-- dwr start -->
<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/dwr/interface/directController.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        //这个方法用来启动该页面的ReverseAjax功能
        dwr.engine.setActiveReverseAjax(true);
        //设置在页面关闭时,通知服务端销毁会话  
        dwr.engine.setNotifyServerOnPageUnload(true);
        //设置DWR调用服务出错时,不打印(alert)调试信息   
        dwr.engine.setErrorHandler(function() {
            //
        });
        onPageLoad();
    })
    function onPageLoad() {
        //这是随机生成的一个类似于id的传到后台
        var a = Math.round(Math.random()*100);
        directController.onPageLoad(a);
    }
    function showMessage(autoMessage) {
        //显示推送的消息
        document.getElementById('dwr_message').innerHTML = autoMessage;
    }
</script>
<-- dwr end -->

这是管理员的页面,填写要推送的消息

//先加载DWR
window.onload = function(){
    onPageLoad();
    dwr.engine.setActiveReverseAjax(true);
    dwr.engine.setNotifyServerOnPageUnload(true);
}

function send(){
    //获取消息
    var message = $("#dwr_mess").val();
    $.ajax({
        url : "sendmessage_dwr?message="+message,
        dataType : "json",
        type : "POST",
        success : function(data) {
            alert("成功");
        },
    });
}

Spring配置文件 添加内容

xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" 
http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd


<!-- 处理静态文件请求,对静态文件不进行 Dispatcher -->
    <mvc:resources mapping="/dwr/**" location="/dwr/" />

<!-- 要求dwr在spring容器中检查拥有@RemoteProxy 和 @RemoteMethod注解的类。注意它不会去检查Spring容器之外的类。 -->  
    <bean id="simpleUrlHandlerMapping"
    class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    <dwr:annotation-config id="dwr" />     <!-- 要求DWR将util.js和engine.js映射到dwrController -->
    <dwr:url-mapping />    <!-- 定义dwr -->
    <dwr:controller id="dwrController" debug="true">
        <dwr:config-param name="allowScriptTagRemoting"
            value="true" />
        <dwr:config-param name="crossDomainSessionSecurity"
            value="false" />
        <dwr:config-param name="classes" value="java.lang.Object" />
        <dwr:config-param name="activeReverseAjaxEnabled"
            value="true" />        <!-- script session 的超时设置 默认值:1800000(30分钟) -->
        <dwr:config-param name="scriptSessionTimeout" value="3600000" />
        <dwr:config-param name="initApplicationScopeCreatorsAtStartup"
            value="true" />
        <dwr:config-param name="org.directwebremoting.extend.ScriptSessionManager"
            value="com.cq.module.dwr_LiuTang.util.DWRScriptSessionManager" />
    </dwr:controller>    <!-- DWR配置 -->

这是DWR的3个固定的类

public class DWRScriptSessionListener implements ScriptSessionListener {
    // 维护一个Map
    // key为session的Id,
    // value为ScriptSession对象
    public static final Map<String, ScriptSession> scriptSessionMap = new HashMap<String, ScriptSession>();

    /**
     * ScriptSession创建事件
     */
    public void sessionCreated(ScriptSessionEvent event) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();
        ScriptSession scriptSession = event.getSession();
        scriptSessionMap.put(session.getId(), scriptSession);
        // 添加 scriptSession
        System.out.println("session: " + session.getId() + " scriptSess ion: "
                + scriptSession.getId() + "is created!");
    }

    /**
     * ScriptSession销毁事件
     */
    public void sessionDestroyed(ScriptSessionEvent event) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();

        ScriptSession scriptSession = scriptSessionMap.remove(session.getId());
        // 移除scriptSession
        System.out.println("session: " + session.getId() + " scriptSess ion: "
                + scriptSession.getId() + "is destroyed!");
    }

    /**
     * 获取所有ScriptSession
     */
    public static Collection<ScriptSession> getScriptSessions() {
        return scriptSessionMap.values();
    }
}

public class DWRScriptSessionManager extends DefaultScriptSessionManager {
    public DWRScriptSessionManager() {
        // 绑定一个ScriptSession增加销毁事件的监听器
        this.addScriptSessionListener(new DWRScriptSessionListener());
    }
}

public class SendMessageAutoUtil {
    // 消息推送 指定某个客户端的页面显示
    public static void sendMessageAuto(String userid, String message,
            String showScriptMethod) {
        final String yhId = userid;
        // 页面标志
        final String autoMessage = message;// 返回的数据
        final String autoShowScriptMethod = showScriptMethod;// 返回页面要调用的JS方法
        // 执行推送
        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
            public boolean match(ScriptSession scriptSession) {
                String yhid = (String) scriptSession.getAttribute("yhId");
                if (yhid != null) {
                    return yhId.equals(yhid);
                } else {
                    return false;
                }
            }
        }, new Runnable() {
            private ScriptBuffer script = new ScriptBuffer();

            public void run() {
                // 设置要调用的 js及参数
                script.appendCall(autoShowScriptMethod, autoMessage);
                // 得到过滤之后的ScriptSession
                Collection<ScriptSession> sessions = Browser
                        .getTargetSessions();
                // 遍历每一个ScriptSession
                for (ScriptSession scriptSession : sessions) {
                    scriptSession.addScript(script);
                }
            }
        });
        // 注意这里调用了有filter功能的方法
    }

    //  有错误
    // 消息推送 指定某个客户端的页面显示 此方法是把要推送的ID放到集合
    public static void sendMessageListAuto(List targetYhidList, String stuxx,
            String showScriptMethod) {
        final List targetIdList = targetYhidList;
        final String autoMessage = stuxx;
        final String autoShowScriptMethod = showScriptMethod;
        // 执行推送
        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
            public boolean match(ScriptSession scriptSession) {
                String yhid = (String) scriptSession.getAttribute("yhId");
                if (yhid != null && targetIdList.contains(yhid)) {
                    // return yhid.equals(yhId);
                    targetIdList.remove(yhid);// 如果找到了,说明将被推送,所以不用再
                                                // 处理,剩下的都是要被处理的
                    return true;
                } else {
                    return false;
                }
            }
        }, new Runnable() {
            private ScriptBuffer script = new ScriptBuffer();

            public void run() {
                // 设置要调用的 js及参数
                script.appendCall(autoShowScriptMethod, autoMessage);
                // 得到过滤之后的ScriptSession
                Collection<ScriptSession> sessions = Browser
                        .getTargetSessions();
                // 遍历每一个ScriptSession
                for (ScriptSession scriptSession : sessions) {
                    scriptSession.addScript(script);
                }
            }

        });
        // 注意这里调用了有filter功能的方法
    }
}

这是我自己写的一个存储id的工具,dwr的那套我看不懂(因为用户不多,所以没考虑并发)

public class IdsList {

    private static Map<String,Date> maps = new HashMap<String, Date>();

    public static void set(String id){
        maps.put(id, new Date());
    }

    public static List<String> get(){
        List<String> result = new ArrayList<String>();
        List<String> mid = new ArrayList<String>();
        long now = new Date().getTime();
        for(String key:maps.keySet()){
            if((now - maps.get(key).getTime()) > 1800000){   //如果时间超过30分钟
                mid.add(key);
            }else{
                result.add(key);
            }
        }
        //删除超过30分钟的数据
        for(String key:mid){
            maps.remove(key);
        }
        return result;
    }
}

这是2个controller

/**
这个对应要显示的页面,  获取随机id
*/
@Controller
@RemoteProxy(name = "directController")
public class DirectController {

    @RemoteMethod
    public void onPageLoad(final String yhId) {
        ScriptSession scriptSession = WebContextFactory.get()
                .getScriptSession();
        scriptSession.setAttribute("yhId", yhId);
        IdsList.set(yhId);
    }

}

/**
 * 发送消息
 * @author LT
 */
@Controller
public class MessageDwrController {

    @RequestMapping("sendmessage_dwr")
    @ResponseBody
    public Boolean aa(String message){
        List<String> ids = IdsList.get();
        for(int i=0;i<ids.size();i++){
            SendMessageAutoUtil.sendMessageAuto(ids.get(i), message, "showMessage");
        }
        return true;
    }
}

欢迎大家指错,谢谢! (自己添加一个DWR的jar包)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值