DWR3.0框架入門(1) —— 實現ajax

框架簡介:DWR(Direct Web Remoting)
     是一個用於改善web頁面與Java類交互的遠程服務器端Ajax開源框架,能夠幫助開發人員開發包含AJAX技術的網站。它能夠容許在瀏覽器裏的代碼使用運行在WEB服務器上的JAVA函數,就像它就在瀏覽器裏同樣。

本Demo實現的基本功能:
點擊jsp界面的按鈕,經過DWR調用到服務器端的java代碼,在控制檯打印出jsp輸入框中的值

Demo構建流程:

1.新建Web工程

2.導入jar包:commons-logging-x.x.x.jar和dwr3.0.jar

3.在web.xml中加入DWR使用能力: javascript

<servlet>  
        <servlet-name> dwr-invoker </servlet-name>  
        <servlet-class> uk.ltd.getahead.dwr.DWRServlet</servlet-class > 
        <init-param>  
            <param-name> debug</param-name > 
            <param-value> true</param-value >
        </init-param>
        <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>
</servlet> 
<servlet-mapping>  
        <servlet-name> dwr-invoker </servlet-name>  
        <url-pattern>/dwr/*</ url-pattern> 
</servlet-mapping>
4.在src中新建類MessagePush:

package sugar.dwr;

public class MessagePush {

        public void send(String str){
              System. out.println(str);
       }
}
5.與web.xml同級目錄下建立dwr.xml,用來配置js函數與java代碼的映射關係:

<?xml version="1.0" encoding= "UTF-8"?> 
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd" > 
<dwr>  
        <allow>  
               <create creator="new" javascript= "messagePush"> 
                      <param name="class" >sugar.dwr.MessagePush</ param> 
               </create>
        </allow>  
</dwr>
6.在index.jsp中寫入js邏輯(該處使用到jquery,請自行添加):

<%@ page language= "java" import ="java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head >
    <title >DWR</ title>
    <script type= "text/javascript" src ="js/jquery-1.8.3.js"></ script>
    <script type= "text/javascript" src ="dwr/util.js"></ script>   
        <script type="text/javascript" src= "dwr/engine.js"></script > 
        <script type="text/javascript" src= "dwr/interface/messagePush.js" ></script>
  </head >
  <body >
        <table border="0" >
               <tr>
                      <td>< input id ="content" type="text" /></td>
                      <td>< input id ="send" type="button" value= "send"/></td >
               </tr>
        </table>
        <script type="text/javascript" >
              $( "#send").click(function(){
                      var content = $("#content" ).val();
                     messagePush.send(content);
              });
        </script>
  </body >
</html>
說明:jsp文件中必須引入幾個js,它們都是隱含存在的,不用考慮它們在哪兒。其中engine.js和util.js是固定的。另外的一個js的名稱就是dwr.xml中配置的類名。

測試結果: html

相關文章
相關標籤/搜索