Java Dwr3實現消息推送步驟詳解

 

        DWR包含兩個主要的部分:允許JavaScript從WEB服務器上一個遵循了AJAX原則的Servlet中獲取數據.另外一方面一個JavaScript庫可以幫助網站開發人員輕鬆地利用獲取的數據來動態改變網頁的內容,DWR採取了一個類似AJAX的新方法來動態生成基於JAVA類的JavaScript代碼。這樣WEB開發人員就可以在JavaScript裏使用Java代碼,就像它們是瀏覽器的本地代碼(客戶端代碼)一樣;但是Java代碼運行在WEB服務器端而且可以自由訪問WEB 服務器的資源。出於安全的理由,WEB開發者必須適當地配置哪些Java類可以安全的被外部使用。下面講解一下具體配置步驟。

 

1、在工程中引入dwr.jar,之後修改配置web.xml文件,添加配置具體代碼如下:

<servlet>
        <servlet-name>dwr-invoker</servlet-name>
        <servlet-class>
            org.directwebremoting.servlet.DwrServlet
        </servlet-class>
        <init-param>
            <param-name>crossDomainSessionSecurity</param-name>
               <param-value>false</param-value>
            </init-param>
        <init-param>
          <param-name>allowScriptTagRemoting</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>classes</param-name>
          <param-value>java.lang.Object</param-value>
        </init-param>
        <init-param>
            <param-name>activeReverseAjaxEnabled</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
           <param-name>initApplicationScopeCreatorsAtStartup</param-name>
           <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>maxWaitAfterWrite</param-name>
            <param-value>3000</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>logLevel</param-name>
            <param-value>WARN</param-value>
        </init-param>
    </servlet>

 

2、在web.xml統計目錄下新增dwr.xml文件,具體內容如下:

<!DOCTYPE dwr PUBLIC
          "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
          "http://getahead.org/dwr/dwr30.dtd">
     <dwr>
          <alow>
               <create creator="new" javascript="MessagePush">
                 <param name="class" value="com.yoodb.service.MessagePush"/>
              </create>
	      <create creator="new" javascript="TestPush">  
                  <param name="class" value="com.yoodb.service.TestPush"/>  
              </create>
          </alow>
     </dwr>

MessagePush在頁面的javascript中使用,com.yoodb.service.MessagePush實現了想要調用的方法,其中MessagePush.java對被推送頁面開放的java類,Test.java是對推送頁面開放的java類。在javascript中使用MessagePush.java類中實現的方法,即可在dwr中調用。

 

3、引入JavaScript文件,具體如下:

<script type="text/javascript" src="<%=basepath%>dwr/engine.js"></script>
<script type="text/javascript" src="<%=basepath%>dwr/util.js"></script>
<script type="text/javascript" src="<%=basepath%>dwr/interface/MessagePush.js"></script>

注意:

1)dwr.xml配置的javascript中engine.js和util.js是必須引入的文件。

2)在任何一個用戶登錄的時候,都需要將其userId或者其他唯一性標識放入session中,我放的是userId,這裏就以userId爲唯一性標識。

3)在載入想推送的頁面時,需要onload一個我在MessagePush類中實現的方法,當然了,需要使用dwr調用

 

被推送html頁面具體內容代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
    <title>DWR  DEMO</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
  </head>  
  <script type='text/javascript' src='dwr/engine.js'></script>  
  <script type='text/javascript' src='dwr/util.js'></script>  
  <script type="text/javascript" src="dwr/interface/MessagePush.js"></script>  
  
  <script type="text/javascript">  
        //通過該方法與後臺交互,確保推送時能找到指定用戶  
         function onPageLoad(){  
            var userId = '${userinfo.userId}';  
            MessagePush.onPageLoad(userId);  
          }  
         //推送信息  
         function showMessage(autoMessage){  
                alert(autoMessage);      
        }  
  </script>  
  <body onload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">   
    This is my DWR DEOM page. <hr>  
    <br>  
    <div id="DemoDiv">demo</div>  
  </body>  
</html>

其中MessagePush.java文件中實現方法,如下:

public class MessagePush{  
	public void onPageLoad(String userId) {  
    	   ScriptSession scriptSession = WebContextFactory.get().getScriptSession();  
   	    scriptSession.setAttribute(userId, userId);  
  	     DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();  
 	      try {  
 	             dwrScriptSessionManagerUtil.init();  
 	             System.out.println("cacaca");  
 	      } catch (ServletException e) {  
 	             e.printStackTrace();  
	       }  
	}  
}

對於onPageLoad()方法中DwrScriptSessionManagerUtil類的實現,具體如下:

import javax.servlet.ServletException;  
import javax.servlet.http.HttpSession;  
  
import org.directwebremoting.Container;  
import org.directwebremoting.ServerContextFactory;  
import org.directwebremoting.WebContextFactory;  
import org.directwebremoting.event.ScriptSessionEvent;  
import org.directwebremoting.event.ScriptSessionListener;  
import org.directwebremoting.extend.ScriptSessionManager;  
import org.directwebremoting.servlet.DwrServlet;  
  
public class DwrScriptSessionManagerUtil extends DwrServlet{  
  
    private static final long serialVersionUID = -7504612622407420071L;  
  
    public void init()throws ServletException {  
  
           Container container = ServerContextFactory.get().getContainer();  
           ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);  
           ScriptSessionListener listener = new ScriptSessionListener() {  
                  public void sessionCreated(ScriptSessionEvent ev) {  
                         HttpSession session = WebContextFactory.get().getSession();  
  
                         String userId =((User) session.getAttribute("userinfo")).getHumanid()+"";  
                         System.out.println("a ScriptSession is created!");  
                         ev.getSession().setAttribute("userId", userId);  
                  }  
                  public void sessionDestroyed(ScriptSessionEvent ev) {  
                         System.out.println("a ScriptSession is distroyed");  
                  }  
           };  
           manager.addScriptSessionListener(listener);  
    }  
}

 

4、推送html頁面具體內容代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
    <title>My JSP 'MyJsp.jsp' starting page</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <script type='text/javascript' src='dwr/engine.js'></script>  
    <script type='text/javascript' src='dwr/util.js'></script>  
    <script type='text/javascript' src='dwr/interface/TestPush.js'></script>  
      
    <script type="text/javascript">  
      
    function testPush() {  
        var msg = document.getElementById("msgId").value;  
        TestPush.sendMessageAuto(msg,"www.yoodb.com");  
          
    }  
    </script>  
  </head>  
    
  <body>  
    id值: <input type="text" name="msgId" id="msgId" /> <br />  
    <input type="button" value="Send" onclick="testPush()"  />  
  </body>  
</html>

其中TeshPush.java文件,具體內容如下:

public class TestPush{  
    public void sendMessageAuto(String userid, String message){  
          
        final String userId = userid;  
        final String autoMessage = message;  
        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {  
            public boolean match(ScriptSession session){  
                if (session.getAttribute("userId") == null)  
                    return false;  
                else  
                    return (session.getAttribute("userId")).equals(userId);  
            }  
        }, new Runnable(){  
              
            private ScriptBuffer script = new ScriptBuffer();  
              
            public void run(){  
                  
                script.appendCall("showMessage", autoMessage);  
                  
                Collection<ScriptSession> sessions = Browser  
  
                .getTargetSessions();  
                  
                for (ScriptSession scriptSession : sessions){  
                    scriptSession.addScript(script);  
                }  
            }  
        });  
    }  
}

來源:http://blog.yoodb.com/yoodb/article/detail/268

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章