• -------------------------------------------------------------
  • ====================================

DWR推送技术运用

未分类 dewbay 5年前 (2019-04-12) 2523次浏览 已收录 1个评论 扫描二维码

Java 代码  

DWR推送技术运用
  1. dwr推送技术的运用  
  2.   
  3. 先说说环境 主要DWR3.0 spring3 springMVC hibernate   
  4. 系统目标 实现服务端主动向客户端推送数据 ,只是客户端打个某个页面,服务端定时向客户端推送新数据刷新客户端页面显示  
  5.   
  6. 集成 spring&MVC +hibernate 后 配置DWR的步骤如下:  
  7. 按惯例从 WEB.xml 讲起   
  8. 添加DWR servlet   
  9.    <listener>  
  10.    <listener-class>com.gzeport.app.gps.dwr.AddScriptSessionListener</listener-class>  
  11.    </listener>  
  12. ///ScriptSession 将页面每个 session 放入一个 map  
  13.      
  14.   <!–dwr servlet–>  
  15.   <servlet>  
  16.     <servlet-name>dwr-invoker</servlet-name>  
  17.     <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>  
  18.     <init-param>  
  19.         <param-name>debug</param-name>  
  20.         <param-value>true</param-value>  
  21.     </init-param>  
  22.     <init-param>  
  23.       <param-name>pollAndCometEnabled</param-name>  
  24.       <param-value>true</param-value>  
  25.     </init-param>  
  26.     <load-on-startup>1</load-on-startup>        
  27.   </servlet>  
  28.     
  29.   <servlet-mapping>    
  30.         <servlet-name>dwr-invoker</servlet-name>    
  31.         <url-pattern>/dwr/*</url-pattern>    
  32.     </servlet-mapping>   
  33.     
  34.   WEB.xml 过滤器配置好后  编写推送程序  
  35.  1—实体对象类 这里随便的示例  
  36. import java.util.Date;  
  37. public class VehicleInfo {  
  38.    
  39.   private   Long   vehicleId;  
  40.   private  String  vTKey;  
  41.   private  String    plate;  
  42.   private  Date     recvtime;  
  43.   private  Date  gpstime;  
  44.   private  String  lat;  
  45.   private  String  lon;  
  46.   private  String  height;  
  47.   private  String  speed;  
  48.   private  String  gpsSpeed;  
  49.   private  String  dir;  
  50.   private  String  mile;  
  51.   private  String  eff;  
  52.   private  String  alarm;  
  53.   private  String  run;  
  54.   private  String  statusChars;  
  55.   private  String  mode;  
  56.   private  String  tagChar;  
  57.   private  String protocol;  
  58.   private  String provider;  
  59.     
  60. public Long getVehicleId() {  
  61.  return vehicleId;  
  62. }  
  63. public void setVehicleId(Long vehicleId) {  
  64.  this.vehicleId = vehicleId;  
  65. }  
  66. ——  
  67. ——这里省去好多 GET,SET 方法  
  68. ——  
  69. public void setProvider(String provider) {  
  70.  this.provider = provider;  
  71. }  
  72. }  
  73.    
  74.  2—ScriptSessionListener   ScriptSession 监听类 AddScriptSessionListener.java  
  75. import java.util.HashMap;  
  76. import java.util.Map;  
  77.   
  78. import org.directwebremoting.Container;  
  79. import org.directwebremoting.ScriptSession;  
  80. import org.directwebremoting.ServerContextFactory;  
  81. import org.directwebremoting.WebContext;  
  82. import org.directwebremoting.WebContextFactory;  
  83. import org.directwebremoting.event.ScriptSessionEvent;  
  84. import org.directwebremoting.event.ScriptSessionListener;  
  85. import org.directwebremoting.extend.ScriptSessionManager;  
  86.   
  87. public class AddScriptSessionListener implements ScriptSessionListener {  
  88.  public static Map<String, ScriptSession> sc=new HashMap<String, ScriptSession>();  
  89.    
  90.  public void sessionCreated(ScriptSessionEvent ev) {  
  91.   WebContext webContext = WebContextFactory.get();   
  92.   sc.put(webContext.getSession().getId(), ev.getSession());  
  93.   System.out.println(“add ———>”+ev.getSession().getId());  
  94.    
  95.  }  
  96.   
  97.  public void sessionDestroyed(ScriptSessionEvent ev) {  
  98.   System.out.println(“remove ———>”+ev.getSession().getId());  
  99.  }  
  100.   
  101. }  
  102.   
  103.   
  104.  3—推送程序类 DwrGpsHelper.java   
  105. import java.util.ArrayList;  
  106. import java.util.Collection;  
  107. import java.util.Iterator;  
  108. import java.util.LinkedList;  
  109. import java.util.Map;  
  110. import java.util.concurrent.locks.ReentrantLock;  
  111. import org.directwebremoting.ScriptBuffer;  
  112. import org.directwebremoting.ScriptSession;  
  113. import org.directwebremoting.WebContext;  
  114. import org.directwebremoting.WebContextFactory;  
  115. import org.directwebremoting.proxy.dwr.Util;  
  116. import com.gzeport.app.gps.dwr.AddScriptSessionListener;  
  117. import com.gzeport.app.gps.pojo.VehicleInfo;  
  118. import com.gzeport.app.gps.thread.ShipDataStore;  
  119.   
  120. public class DwrGpsHelper {     
  121.     private static ArrayList<VehicleInfo> messages = new ArrayList<VehicleInfo>();     
  122.     private static ReentrantLock lock = new ReentrantLock(); //JDK5 锁     
  123.       
  124.     private ShipDataStore shipDataStore = null;  
  125.      
  126.  public void addMessage(){     
  127.         try{     
  128.             lock.lock();    
  129.             System.out.println(“进入调度程序……….”);  
  130.             messages = (ArrayList<VehicleInfo>) shipDataStore.getShipListData();  
  131.            System.out.println(“取得数据:”+messages.size());  
  132.             for(VehicleInfo vehicleInfo :messages){  
  133.              if(vehicleInfo!=null){  
  134.               System.out.println(“准备推送数据:”+vehicleInfo.getVTKey());  
  135.              }  
  136.             }  
  137.         }catch(Exception ex){     
  138.             ex.printStackTrace();     
  139.         }finally{     
  140.             lock.unlock();     
  141.         }               
  142.          Collection<ScriptSession> sessions =new LinkedList() ;  
  143.           
  144.         Map map=AddScriptSessionListener.sc;  
  145.       Iterator<String> it = map.keySet().iterator();  
  146.       StringBuffer sb = new StringBuffer();  
  147.       int index =0;  
  148.       if (it!=null){  
  149.        while(it.hasNext()){  
  150.         String key1 = it.next();  
  151.         sessions.add((ScriptSession)map.get(key1));  
  152.        }  
  153.       }  
  154.       System.out.println(“SSS–>”+sessions.size());  
  155.         if(sessions!=null&&sessions.size()>0){  
  156.            
  157.         }else{  
  158.          System.out.println(“sessions is null”);           
  159.         }  
  160.            Util utilAll = new Util(sessions);                   
  161.            //执行客户端脚本     
  162.            ScriptBuffer script = new ScriptBuffer();     
  163.            script.appendScript(“clientFunction(“)     
  164.   
  165.             .appendData(messages)   
  166.              .appendScript(“);”);     
  167.                 
  168.            for(ScriptSession session: sessions){     
  169.                session.addScript(script);     
  170.            }                   
  171.            //更新这些脚本 session 的一些元素     
  172.          //  utilAll.removeAllOptions(“messages”);     
  173.          //  utilAll.addOptions(“messages”, messages, “vTKey”, “statusChars”);  
  174.        }        
  175.  public ShipDataStore getShipDataStore() {  
  176.   return shipDataStore;  
  177.  }  
  178.     
  179.  public void setShipDataStore(ShipDataStore shipDataStore) {  
  180.   this.shipDataStore = shipDataStore;  
  181.  }  
  182.     
  183. }    
  184.   
  185. 4—–DWR.xml 配置文件的配置   
  186. <!– 业务处理类  交给 spring–>   
  187.  <create creator=”spring” javascript=”dwrGpsHelper” scope=”application”>  
  188.    <param name=”beanName” value=”dwrGpsHelper”/>   
  189.  </create>  
  190.   
  191.  <!–     convert 将 bean 的集合变成 javascript 中的对象数组–>  
  192.    
  193.  <convert converter=”bean” match=”com.gzeport.app.gps.pojo.VehicleInfo”>  
  194.   <param name=”include” value=”alarm,dir,eff,mode,gpsSpeed,gpstime,height,lat,lon,mile,plate,protocol,provider,recvtime,  
  195.          run,speed,statusChars,tagChar,vehicleId,vTKey”/>  
  196.  </convert>             
  197.    </allow>  
  198. 5– spring bean 配置   
  199.      <bean id=”dwrGpsHelper” class=”com.gzeport.app.gps.dwr.controller.DwrGpsHelper”>   
  200.       <property name=”shipDataStore”>  
  201.        <ref bean=”shipDataStore” />  
  202.       </property>   
  203.      <dwr:remote javascript=”dwrGpsHelper”>    
  204.        <dwr:include method=”addMessage” />       
  205.      </dwr:remote>  
  206.     </bean>  
  207.       
  208. 6—-JSP 页面 showdata.jsp  
  209. <%@ page language=”java” pageEncoding=”UTF-8″%>    
  210. <%@ page import=”org.directwebremoting.ServerContextFactory” %>  
  211. <%@ page import=”org.directwebremoting.Container” %>  
  212. <%@ page import=”com.gzeport.app.gps.dwr.AddScriptSessionListener” %>  
  213. <%@ page import=”org.directwebremoting.extend.ScriptSessionManager” %>  
  214.    
  215. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>   
  216. <%  
  217. String path = request.getContextPath();  
  218. String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;  
  219.    
  220. %>   
  221. <%String root=request.getContextPath();%>   
  222. <%  
  223.   //添加监听器  
  224.     Container container = ServerContextFactory.get().getContainer();    
  225.  ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);    
  226.  manager.addScriptSessionListener(new AddScriptSessionListener());   
  227.   %>  
  228. <html>    
  229.   <head>  
  230. <script type=’text/javascript’ src='<%=root%>/dwr/engine.js’></script>    
  231.     <script type=’text/javascript’ src='<%=root%>/dwr/util.js’></script>    
  232. <!–    <script type=’text/javascript’ src='<%=root%>/dwr/interface/dwrVehicleInfoService.js’></script>  –>  
  233.   <script type=’text/javascript’ src='<%=root%>/dwr/interface/dwrGpsHelper.js’></script>  
  234. </head>    
  235.        
  236.   <!– 通过 dwr.engine.setActiveReverseAjax(true); 启动该页面的 Reverse Ajax 功能  –>    
  237.   <body onload=”dwr.engine.setActiveReverseAjax(true);dwr.engine.setErrorHandler(function(){})”>   //反转需要加上这两个   
  238. <!–    <p>输入信息: <input id=”text” onkeypress=”dwr.util.onReturn(event, getMessage)” />    –>  
  239. <!–    <input type=”button” value=”Send” onclick=”getMessage()()” /></p>  –>  
  240. <!–  –>  
  241.  <p>从后台推送回的数据: </p>  
  242. <!– <input id=”text” />  –>  
  243.     <script type=”text/javascript”>  
  244.      function sendMessage() {     
  245.             dwrVehicleInfoService.perform();     
  246.         }   
  247.          function putInfo(serverdata){  
  248.         for(var i =0;i<serverdata.length;i++){  
  249.        // alert(serverdata[i]);  
  250.          var obj =dwr.util.toDescriptiveString(serverdata[i], 20);  
  251.         // alert(dwr.util.toDescriptiveString(serverdata[i], 20));  
  252.         }  
  253.       // alert(serverdata.length);  
  254.         }          
  255.          function clientFunction(serverdata){  
  256.          for(var i =0;i<serverdata.length;i++){  
  257.         // alert(serverdata[i]);  
  258.           var obj =dwr.util.toDescriptiveString(serverdata[i], 20);  
  259.          // alert(dwr.util.toDescriptiveString(serverdata[i], 20));  
  260.          }  
  261.        alert(serverdata);  
  262.         }      
  263.    </script>         
  264.     <hr/>    
  265. <!–    <select id=”messages”></select>  –>  
  266.      <div id=”showdata”>  
  267.      </div>  
  268.       
  269.   </body>    
  270. </html>    
  271.   
  272. 7—–配置一个调度器 定时推送一次数据到页面   
  273.   
  274.  <!–Quartz –>  
  275.  <!– 调度获取数据 –>  
  276.  <bean id=”getDwrGpsHelperJobDetail” class=”org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean”  
  277.   p:targetObject-ref=”dwrGpsHelper”    
  278.   p:targetMethod=”addMessage” />  
  279.    
  280.  <bean id=”triggergetGpsShipDataCleaner” class=”org.springframework.scheduling.quartz.SimpleTriggerBean”  
  281.   p:jobDetail-ref=”getDwrGpsHelperJobDetail”  
  282.   p:startDelay=”20000″  
  283.   p:repeatInterval=”15000″ />  
  284.    
  285.  <!– Spring 触发工厂 –>    
  286.     <bean class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>    
  287.        <property name=”triggers”>    
  288.             <list>    
  289.                <ref bean=”triggergetGpsShipDataCleaner”/>    
  290.                <!– ….下面可以继续添加其他触发器 –>    
  291.            </list>    
  292.       </property>    
  293.     </bean>    
  294.       
  295.       
  296.     至此 大致完成 dwr 推送程序的示例   将每隔 15000 纳秒推送一次数据   
  297.     

露水湾 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:DWR推送技术运用
喜欢 (0)
[]
分享 (0)
关于作者:
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽
  1. 看看
    1123122020-10-23 15:07 回复 Windows 10 | Chrome 86.0.4240.75