1.web.xmljavascript
1 <servlet> 2 <servlet-name>dwr-invoker</servlet-name> 3 <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> 4 <init-param> 5 <param-name>debug</param-name> 6 <param-value>true</param-value> 7 </init-param> 8 </servlet> 9 10 <servlet-mapping> 11 <servlet-name>dwr-invoker</servlet-name> 12 <url-pattern>/dwr/*</url-pattern> 13 </servlet-mapping>
2.dwr.xml前端
<?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> <!-- 創建JS對象,將目標對象的方法轉換成JS對象的方法 --> <create javascript="helloSrv" creator="new"> <param name="class" value="services.HelloServices"></param> </create> <!-- 從Spring中獲取Java對象 --> <create javascript="deptSrv" creator="spring"> <param name="beanName" value="deptServices"></param> <!-- 禁止執行 --> <exclude method="deleteDept" /> </create> <create javascript="loginSrv" creator="spring"> <param name="beanName" value="loginSrv"></param> </create> <!-- 指定針對於特定對象的轉換器 --> <convert match="entity.*" converter="bean"></convert> <convert match="java.lang.Throwable" converter="bean"> <param name="include" value="message"></param> </convert> </allow> </dwr>
3.前端js代碼java
<!-- 記得引入js,測試地址: http://localhost:8083/dwrweb/dwr/ --> <script type="text/javascript" src="dwr/engine.js"></script> <script type="text/javascript" src="dwr/interface/helloSrv.js"></script> <script type="text/javascript" src="dwr/util.js"></script> <script type="text/javascript"> function hello(){ //方法一 //返回處理後的結果信息 /*var fn = function(result){ $("msg").innerHTML = result; } helloSrv.sayHello($("name").value, fn);*/ //方法二 helloSrv.sayHello($("name").value, function(result){ $("msg").innerHTML=result; }); //方法三 //使用以下的好處爲:不用導入如上三個js //第一個參數: dwr訪問路徑,在web.xml中配置,如: <url-pattern>/dwr/*</url-pattern> //第二個參數: dwr與java服務器通訊變量,在dwr.xml中聲明 //第三個參數: 服務器方法名 //第四個參數: 頁面請求參數,即服務器方法名得參數 //第五個參數: 回調函數 //dwr.engine._execute("dwr", 'helloSrv', 'sayHello', $("name").value, fn); } </script>