DWR第一篇之入門示例
阿新 • • 發佈:2017-08-30
es2017 blog gets 測試 sky limit 目錄結構 rpo contex
1. 新建maven-web項目,目錄結構如下:
2. 在pom.xml裏添加dwr所需的依賴
1 <dependency> 2 <groupId>org.directwebremoting</groupId> 3 <artifactId>dwr</artifactId> 4 <version>3.0.1-RELEASE</version> 5 </dependency> 6 <dependency> 7 <groupId>commons-logging</groupId> 8 <artifactId>commons-logging</artifactId> 9 <version>1.2</version> 10 </dependency>
3. 在web.xml裏邊添加dwr的servlet配置
1 <!-- 配置dwr請求的servlet --> 2 <servlet> 3 <servlet-name>dwr-invoker</servlet-name> 4 <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> 5 </servlet> 6 <servlet-mapping> 7 <servlet-name>dwr-invoker</servlet-name> 8 <url-pattern>/dwr/*</url-pattern> 9 </servlet-mapping>
4. 新建核心控制器類CoreServlet.java(註意:這裏只是普通的java類,不是servlet)
1 package com.skyer.servlet; 2 3 public class CoreServlet { 4 public void sayHello() { 5 System.out.println("Hello World!"); 6 } 7 8 public String getHello(String name) { 9 return "Hello " + name; 10 } 11 }
5. 在WEB_INF根目錄下添加dwr.xml文件:
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> <dwr> <allow> <create creator="new" javascript="CoreServlet"> <param name="class" value="com.skyer.servlet.CoreServlet" /> </create> </allow> </dwr>
6. 新建測試用的jsp頁面index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>dwr_demo</title> 13 <script type=‘text/javascript‘ src=‘dwr/engine.js‘></script> 14 <script type=‘text/javascript‘ src=‘dwr/util.js‘></script> 15 <script type=‘text/javascript‘ src=‘dwr/interface/CoreServlet.js‘></script> 16 </head> 17 18 <body> 19 <input type="button" value="發送" onclick="sayHello();"> 20 <br> 21 <input type="text" id="getHello"> 22 <br> 23 <input type="button" value="發送" onclick="getHello();"> 24 <br> 25 <input type="text" id="getHelloValue"> 26 </body> 27 <script type="text/javascript"> 28 function sayHello() { 29 CoreServlet.sayHello(); 30 } 31 function getHello() { 32 var name = dwr.util.getValue("getHello"); 33 CoreServlet.getHello(name, function(data) { 34 dwr.util.setValue("getHelloValue", data); 35 }); 36 } 37 </script> 38 </html>
註意,JSP文件裏引入了三個js包,其中engine.js和util.js是dwr裏自帶的js文件,添加到項目裏即可。另外一個CoreServlet.js文件需要自己手動建立,其路徑必須在dwr/interface,名稱必須和dwr.xml配置文件裏的javascript屬性一致。下面的js腳本調用了CoreServlet裏的方法。
7. 測試(註意:需要JDK1.7及以上)
DWR第一篇之入門示例