新人 熟手 專家 大師 宗師 ...

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            2 Posts :: 0 Stories :: 5 Comments :: 0 Trackbacks
             場景:頁面comet.jsp接受服務器推送的信息并顯示,頁面action.jsp執行一個動作,調用DwrServer.perform方法,perform方法做某些事,并發送事件信息PerformInfo。NotifyClient監聽事件,當接收到PerformInfo后,把PerformInfo的信息發送到comet.jsp頁面。這個場景模擬了頁面1執行了一個時間比較長或復雜的任務,任務執行情況可以反饋到頁面2(比如模式窗口)。
             信息載體PerformInfo.java
          package application.comet;

          import java.util.Date;

          public class PerformInfo {
            
          private int id;
            
          private String msg;
            
          private Date   time;
            
          /**
             * 
          @return the id
             
          */
            
          public int getId() {
              
          return id;
            }
            
          /**
             * 
          @param id the id to set
             
          */
            
          public void setId(int id) {
              
          this.id = id;
            }
            
          /**
             * 
          @return the msg
             
          */
            
          public String getMsg() {
              
          return msg;
            }
            
          /**
             * 
          @param msg the msg to set
             
          */
            
          public void setMsg(String msg) {
              
          this.msg = msg;
            }
            
          /**
             * 
          @return the time
             
          */
            
          public Date getTime() {
              
          return time;
            }
            
          /**
             * 
          @param time the time to set
             
          */
            
          public void setTime(Date time) {
              
          this.time = time;
            }

          }
             Spring的事件InfoEvent.java
          package application.comet;

          import org.springframework.context.ApplicationEvent;

          public class InfoEvent extends ApplicationEvent {
             
          public InfoEvent(Object source){
               
          super(source);
             }
          }

             DwrService.java 執行任務,就是寫了100遍PerformInfo,需要實現ApplicationContextAware接口
          package application.comet;

          import java.util.Date;

          import org.springframework.context.ApplicationContext;
          import org.springframework.context.ApplicationContextAware;
          import org.springframework.context.ApplicationEvent;

          public class DwrService implements ApplicationContextAware{
            
          private ApplicationContext ctx;
            
          public void setApplicationContext(ApplicationContext ctx) {
              
          this.ctx = ctx;
            }
            
          public void perform(){
              
          for (int i=0;i<100;i++){
                PerformInfo info 
          = new PerformInfo();
                info.setId(i);
                info.setMsg(
          "發送"+i+"信息");
                info.setTime(
          new Date());
                InfoEvent evt 
          = new InfoEvent(info);
                ctx.publishEvent(evt);
              }
            }

          }

          NotifyClient.java監聽事件,發送信息到頁面。實現ApplicationListener,ServletContextAware接口,對中文需要編碼
          package application.comet;

          import java.io.UnsupportedEncodingException;
          import java.util.Collection;

          import javax.servlet.ServletContext;
          import javax.servlet.http.HttpSession;
          import javax.servlet.http.HttpSessionBindingEvent;
          import org.springframework.web.context.ServletContextAware;
          import org.directwebremoting.ScriptBuffer;
          import org.directwebremoting.ScriptSession;
          import org.directwebremoting.ServerContext;
          import org.directwebremoting.ServerContextFactory;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.ApplicationContextAware;
          import org.springframework.context.ApplicationEvent;
          import org.springframework.context.ApplicationListener;

          public class NotifyClient implements ApplicationListener,ServletContextAware{
            
          private ServletContext servletContext = null;
            
          public void setServletContext( ServletContext servletContext )
            {
              
          this.servletContext = servletContext;
            }    
            
            
          public void onApplicationEvent(ApplicationEvent event) {
              
          if (event instanceof InfoEvent) {
                PerformInfo info 
          = (PerformInfo)event.getSource();
                System.out.println(info.getMsg());
                
          //Collection<ScriptSession> sessions=ctx.getAllScriptSessions();
                ServerContext ctx = ServerContextFactory.get(servletContext );
                Collection
          <ScriptSession> sessions = 
                     ctx.getScriptSessionsByPage(
          "/dwrcomet/comet.jsp");  
                
          for (ScriptSession session : sessions) {
                    ScriptBuffer script 
          = new ScriptBuffer();
                    String s
          =null;
                    String s2 
          = null;
                    
          try {
                      s 
          = java.net.URLEncoder.encode(info.getMsg(),"UTF-8");
                      s2 
          = java.net.URLEncoder.encode("通知結束","UTF-8");
                    } 
          catch (UnsupportedEncodingException e) {
                      e.printStackTrace();
                    }
                    
          if (info.getId()<99){
                      script.appendScript(
          "putInfo('")
                      .appendScript(info.getId()
          +":"+s)
                      .appendScript(
          "');");
                    }
          else{
                      script.appendScript(
          "alert(decodeURI('").
                             appendScript(s2).appendScript(
          "'));");
                    }
                    
                    System.out.println(script.toString());
                    session.addScript(script);
                }        
              }
            }

          }

          action.jsp執行任務
          <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
          <%
          String root 
          = request.getContextPath();
          %>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
            
          <head>
              
          <title>doing</title>
              
              
          <meta http-equiv="pragma" content="no-cache">
              
          <meta http-equiv="cache-control" content="no-cache">
              
          <meta http-equiv="expires" content="0">    
          <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/DwrService.js'></script>
            
          </head>
            
            
          <body>
            
          <input name='action' onclick='DwrService.perform();' type="button" value="行動"/>
            
          </body>
          </html>

          comet.jsp接受信息。關鍵是增加onload="dwr.engine.setActiveReverseAjax(true);",還可以根據user或session id判斷是否是自己的信息.
          <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
          <%
          String root 
          = request.getContextPath();
          String basePath 
          = request.getScheme()+"://"+request.getServerName()+":"
          +request.getServerPort()+root+"/";
          %>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
            
          <head>
              
          <base href="<%=basePath%>">
              
              
          <title>Comet with DWR</title>
              
              
          <meta http-equiv="pragma" content="no-cache">
              
          <meta http-equiv="cache-control" content="no-cache">
              
          <meta http-equiv="expires" content="0">    
            
          </head>
            
          <body onload="dwr.engine.setActiveReverseAjax(true);">
          <script type='text/javascript' src='<%=root%>/dwr/engine.js'></script>
          <script type='text/javascript' src='<%=root%>/dwr/util.js'></script>
          <script type="text/javascript">
              var user 
          = '<%=request.getParameter("user")%>';
              
              function putInfo(data) {
                 var d 
          = decodeURI(data);
                 var text 
          = dwr.util.getValue('info');       
                 dwr.util.setValue(
          'info',text+'\n'+d);
              }
          </script>
          <br/>
          <textarea rows="20" cols="100" id='info'></textarea>
          </body>
          </html>

          applicationContext.xml配置了NotifyClient和DwrService,這兩個bean實現了ApplicationContextAware
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
          <beans>
            
          <bean id="notifyClient" class="application.comet.NotifyClient">
            
          </bean>
            
          <bean id="dwrService" class="application.comet.DwrService"></bean>
          </beans>

          dwr.xml
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE dwr PUBLIC
              "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
              "http://www.getahead.ltd.uk/dwr/dwr10.dtd"
          >
          <dwr>
            
          <allow>
              
          <create creator="spring" javascript="DwrService">
                
          <param name="beanName" value="dwrService" />
              
          </create>
            
          </allow>
          </dwr>


          web.xml定義了dwr的comet控制,關鍵是pollAndCometEnabled=true
          <?xml version="1.0" encoding="UTF-8"?>
          <web-app version="2.4" 
              xmlns
          ="http://java.sun.com/xml/ns/j2ee" 
              xmlns:xsi
          ="http://www.w3.org/2001/XMLSchema-instance" 
              xsi:schemaLocation
          ="http://java.sun.com/xml/ns/j2ee 
              http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
          >
              
          <context-param>
                  
          <param-name>contextConfigLocation</param-name>
                  
          <param-value>/WEB-INF/app*.xml</param-value>
              
          </context-param>
              
          <servlet>
                  
          <servlet-name>context</servlet-name>
                  
          <servlet-class>
                      org.springframework.web.context.ContextLoaderServlet
                  
          </servlet-class>
                  
          <load-on-startup>1</load-on-startup>
              
          </servlet>

           
          <!--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-app>

          運行時要先打開comet.jsp,然后執行action.jsp

          posted on 2008-07-04 11:46 記憶力 閱讀(4520) 評論(3)  編輯  收藏 所屬分類: ajax

          Feedback

          # re: dwr做comet的完整實現 2008-12-15 17:07 楊俊
          有DwrService.js文件么  回復  更多評論
            

          # re: dwr做comet的完整實現[未登錄] 2009-08-31 14:17 阿哲
          現在我這個能跑得起來

          但是comet.jsp

          沒有數據顯示阿

          砸毀尸阿  回復  更多評論
            

          # re: dwr做comet的完整實現 2011-01-23 11:51 fengyp
          NotifyClient.java中Collection<ScriptSession> sessions =
          ctx.getScriptSessionsByPage("/dwrcomet/comet.jsp");
          記得改dwrcomet為自己的應用名  回復  更多評論
            


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 徐汇区| 秭归县| 铜鼓县| 鹤庆县| 察哈| 东平县| 色达县| 依兰县| 高安市| 安乡县| 江川县| 楚雄市| 凤翔县| 大足县| 宁明县| 昭觉县| 鲁山县| 阳原县| 拜城县| 九龙坡区| 资阳市| 柳州市| 赣榆县| 高碑店市| 六盘水市| 平顶山市| 德保县| 汉沽区| 广元市| 柳林县| 邛崃市| 凤翔县| 正蓝旗| 五莲县| 綦江县| 灌阳县| 大关县| 尼木县| 永仁县| 井研县| 保康县|