DWR 消息推送
2016-05-13 17:00
375 查看
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包)
相关文章推荐
- 网络扫盲——NAT(网络地址转换)
- Linux下项目与事务跟踪工具JIRA搭建汉化安装详解
- C++的常量引用
- android SeekBar的自定义样式设置
- Jetty的安装和配置
- java中文乱码解决之道(二)—–字符编码详解:基础知识 + ASCII + GB**
- Android中activity保存状态和数据到底该在哪个方法中进行
- Could not obtain transaction-synchronized Session for current thread
- 读nandflash详解
- 判断两条直线是否相交
- java 反编译和引用jar包的方法
- 【搞定配色】超实用!帮你快速搞定网页配色的方法(附配色神器)
- 【BZOJ4439】[Swerc2015]Landscaping【最小割】
- CodeForces - 96B Lucky Numbers (easy)
- POJ 1696 Space Ant Graham-scan
- 励志学习文章精选
- hdu1495非常可乐(BFS)
- 机器学习开源代码大集合
- 深度学习BP算法的推导附加RNN-LSTM的推导
- myeclipse中打开java文件中文乱码