DWR推送技术运用

dwr推送技术的运用

先说说环境 主要DWR3.0 spring3 springMVC hibernate 
系统目标 实现服务端主动向客户端推送数据 ,只是客户端打个某个页面,服务端定时向客户端推送新数据刷新客户端页面显示

集成spring&MVC +hibernate后 配置DWR的步骤如下:
按惯例从WEB.xml讲起 
添加DWR servlet 
   <listener>
   <listener-class>com.gzeport.app.gps.dwr.AddScriptSessionListener</listener-class>
   </listener>
///ScriptSession将页面每个session放入一个map
   
  <!--dwr servlet-->
  <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>
      <param-name>pollAndCometEnabled</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>      
  </servlet>
  
  <servlet-mapping>  
        <servlet-name>dwr-invoker</servlet-name>  
        <url-pattern>/dwr/*</url-pattern>  
    </servlet-mapping> 
  
  WEB.xml过滤器配置好后  编写推送程序
 1---实体对象类 这里随便的示例
import java.util.Date;
public class VehicleInfo {
 
  private   Long   vehicleId;
  private  String  vTKey;
  private  String    plate;
  private  Date     recvtime;
  private  Date  gpstime;
  private  String  lat;
  private  String  lon;
  private  String  height;
  private  String  speed;
  private  String  gpsSpeed;
  private  String  dir;
  private  String  mile;
  private  String  eff;
  private  String  alarm;
  private  String  run;
  private  String  statusChars;
  private  String  mode;
  private  String  tagChar;
  private  String protocol;
  private  String provider;
  
public Long getVehicleId() {
 return vehicleId;
}
public void setVehicleId(Long vehicleId) {
 this.vehicleId = vehicleId;
}
------
------这里省去好多GET,SET方法
------
public void setProvider(String provider) {
 this.provider = provider;
}
}
 
 2---ScriptSessionListener   ScriptSession监听类 AddScriptSessionListener.java
import java.util.HashMap;
import java.util.Map;

import org.directwebremoting.Container;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;

public class AddScriptSessionListener implements ScriptSessionListener {
 public static Map<String, ScriptSession> sc=new HashMap<String, ScriptSession>();
 
 public void sessionCreated(ScriptSessionEvent ev) {
  WebContext webContext = WebContextFactory.get(); 
  sc.put(webContext.getSession().getId(), ev.getSession());
  System.out.println("add --------->"+ev.getSession().getId());
 
 }

 public void sessionDestroyed(ScriptSessionEvent ev) {
  System.out.println("remove --------->"+ev.getSession().getId());
 }

}


 3---推送程序类 DwrGpsHelper.java 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import com.gzeport.app.gps.dwr.AddScriptSessionListener;
import com.gzeport.app.gps.pojo.VehicleInfo;
import com.gzeport.app.gps.thread.ShipDataStore;

public class DwrGpsHelper {   
    private static ArrayList<VehicleInfo> messages = new ArrayList<VehicleInfo>();   
    private static ReentrantLock lock = new ReentrantLock(); //JDK5锁   
    
    private ShipDataStore shipDataStore = null;
   
 public void addMessage(){   
        try{   
            lock.lock();  
            System.out.println("进入调度程序..........");
            messages = (ArrayList<VehicleInfo>) shipDataStore.getShipListData();
           System.out.println("取得数据:"+messages.size());
            for(VehicleInfo vehicleInfo :messages){
             if(vehicleInfo!=null){
              System.out.println("准备推送数据:"+vehicleInfo.getVTKey());
             }
            }
        }catch(Exception ex){   
            ex.printStackTrace();   
        }finally{   
            lock.unlock();   
        }             
         Collection<ScriptSession> sessions =new LinkedList() ;
        
        Map map=AddScriptSessionListener.sc;
      Iterator<String> it = map.keySet().iterator();
      StringBuffer sb = new StringBuffer();
      int index =0;
      if (it!=null){
       while(it.hasNext()){
        String key1 = it.next();
        sessions.add((ScriptSession)map.get(key1));
       }
      }
      System.out.println("SSS-->"+sessions.size());
        if(sessions!=null&&sessions.size()>0){
         
        }else{
         System.out.println("sessions is null");         
        }
           Util utilAll = new Util(sessions);                 
           //执行客户端脚本   
           ScriptBuffer script = new ScriptBuffer();   
           script.appendScript("clientFunction(")   

            .appendData(messages) 
             .appendScript(");");   
              
           for(ScriptSession session: sessions){   
               session.addScript(script);   
           }                 
           //更新这些脚本session的一些元素   
         //  utilAll.removeAllOptions("messages");   
         //  utilAll.addOptions("messages", messages, "vTKey", "statusChars");
       }      
 public ShipDataStore getShipDataStore() {
  return shipDataStore;
 }
  
 public void setShipDataStore(ShipDataStore shipDataStore) {
  this.shipDataStore = shipDataStore;
 }
  
}  

4-----DWR.xml配置文件的配置 
<!-- 业务处理类  交给spring--> 
 <create creator="spring" javascript="dwrGpsHelper" scope="application">
   <param name="beanName" value="dwrGpsHelper"/> 
 </create>

 <!--     convert将bean的集合变成javascript中的对象数组-->
 
 <convert converter="bean" match="com.gzeport.app.gps.pojo.VehicleInfo">
  <param name="include" value="alarm,dir,eff,mode,gpsSpeed,gpstime,height,lat,lon,mile,plate,protocol,provider,recvtime,
         run,speed,statusChars,tagChar,vehicleId,vTKey"/>
 </convert>           
   </allow>
5-- spring bean 配置 
     <bean id="dwrGpsHelper" class="com.gzeport.app.gps.dwr.controller.DwrGpsHelper"> 
      <property name="shipDataStore">
       <ref bean="shipDataStore" />
      </property> 
     <dwr:remote javascript="dwrGpsHelper">  
       <dwr:include method="addMessage" />     
     </dwr:remote>
    </bean>
    
6----JSP页面 showdata.jsp
<%@ page language="java" pageEncoding="UTF-8"%>  
<%@ page import="org.directwebremoting.ServerContextFactory" %>
<%@ page import="org.directwebremoting.Container" %>
<%@ page import="com.gzeport.app.gps.dwr.AddScriptSessionListener" %>
<%@ page import="org.directwebremoting.extend.ScriptSessionManager" %>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 
%> 
<%String root=request.getContextPath();%> 
<%
  //添加监听器
    Container container = ServerContextFactory.get().getContainer();  
 ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);  
 manager.addScriptSessionListener(new AddScriptSessionListener()); 
  %>
<html>  
  <head>
<script type='text/javascript' src='<%=root%>/dwr/engine.js'></script>  
    <script type='text/javascript' src='<%=root%>/dwr/util.js'></script>  
<!--    <script type='text/javascript' src='<%=root%>/dwr/interface/dwrVehicleInfoService.js'></script>  -->
  <script type='text/javascript' src='<%=root%>/dwr/interface/dwrGpsHelper.js'></script>
</head>  
     
  <!-- 通过 dwr.engine.setActiveReverseAjax(true); 启动该页面的Reverse Ajax功能  -->  
  <body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setErrorHandler(function(){})">   //反转需要加上这两个 
<!--    <p>输入信息: <input id="text" onkeypress="dwr.util.onReturn(event, getMessage)" />    -->
<!--    <input type="button" value="Send" onclick="getMessage()()" /></p>  -->
<!--  -->
 <p>从后台推送回的数据: </p>
<!-- <input id="text" />  -->
    <script type="text/javascript">
     function sendMessage() {   
            dwrVehicleInfoService.perform();   
        } 
         function putInfo(serverdata){
        for(var i =0;i<serverdata.length;i++){
       // alert(serverdata[i]);
         var obj =dwr.util.toDescriptiveString(serverdata[i], 20);
        // alert(dwr.util.toDescriptiveString(serverdata[i], 20));
        }
      // alert(serverdata.length);
        }        
         function clientFunction(serverdata){
         for(var i =0;i<serverdata.length;i++){
        // alert(serverdata[i]);
          var obj =dwr.util.toDescriptiveString(serverdata[i], 20);
         // alert(dwr.util.toDescriptiveString(serverdata[i], 20));
         }
       alert(serverdata);
        }    
   </script>       
    <hr/>  
<!--    <select id="messages"></select>  -->
     <div id="showdata">
     </div>
    
  </body>  
</html>  

7-----配置一个调度器 定时推送一次数据到页面 

 <!--Quartz -->
 <!-- 调度获取数据 -->
 <bean id="getDwrGpsHelperJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
  p:targetObject-ref="dwrGpsHelper"  
  p:targetMethod="addMessage" />
 
 <bean id="triggergetGpsShipDataCleaner" class="org.springframework.scheduling.quartz.SimpleTriggerBean"
  p:jobDetail-ref="getDwrGpsHelperJobDetail"
  p:startDelay="20000"
  p:repeatInterval="15000" />
 
 <!-- Spring触发工厂 -->  
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
       <property name="triggers">  
            <list>  
               <ref bean="triggergetGpsShipDataCleaner"/>  
               <!-- ....下面可以继续添加其他触发器 -->  
           </list>  
      </property>  
    </bean>  
    
    
    至此 大致完成dwr推送程序的示例   将每隔15000纳秒推送一次数据 
  

你可能感兴趣的:(DWR)