1.创建一个Web Project项目,向WEB-INF/lib/目录包里面导入dwr.jar
2.修改web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- dwr核心servlet --> <listener> <listener-class>org.directwebremoting.servlet.DwrListener</listener-class> </listener> <servlet> <!-- dwr核心servelt实现类 --> <servlet-name>dwr</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!-- 设置dwr可调式 --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3.创建一个DwrService.java类
package com.yjpeng.dwr; public class DwrService { public String sayHello(String message){ return "欢迎使用DWR" + message; } }
4.在WEB-INF目录下创建一个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> <create creator="new" javascript="dwrService" scope="application"> <param name="class" value="com.yjpeng.dwr.DwrService"></param> </create> </allow> </dwr>
5.修改index.jsp文件代码
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% 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 'index.jsp' starting page</title> <script src="dwr/interface/dwrService.js"></script> <script src="dwr/engine.js" ></script> <script type="text/javascript"> function aa(){ dwrService.sayHello("assd", bb); } function bb(data){ document.getElementById("message").value = data; } </script> </head> <body> <input type="text" id="message"/> <input type="button" value="callDwr" onclick="aa();" /> </body> </html>
6.把web项目部署到服务器中,在浏览器中输入相应的URL。最后测试成功会在文本框里面出现 “assd” 字符串。