转自:
第一个DWR程序
dwr插件的作用就是让js可以访问后台的java类 一、添加DWR支持新建dynamic web project项目名称为test_dwr,下载dwr.jar包,放入WEB-INF/lib目录 二、编辑配置文件web.xml,添加servlet添加如下的servlet到web.xml <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>debug</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> 三、创建Hello.java类,用来为前台js提供服务package com.mfanw; public class Hello { public String sayHello(String name){ return "Hello, " + name + ", Welcome."; } } 四、WEB-INF目录下创建dwr.xml文件,并配置好Hello类<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" ""> <dwr> <allow> <create creator="new" javascript="service"> <param name="class" value="com.mfanw.Hello" /> </create> </allow> </dwr>service的名字表示在js中引用他是service对象
五、测试DWR的连通性。访问:端口/项目名/dwr,若是出现 service (NewCreator for com.mfanw.Hello) 则表示配置成功 点击这个service可以查看配置方法和使用方法。 六、编写前台测试页面index.jsp其中test_dwr为项目名称。 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type='text/javascript' src='/test_dwr/dwr/engine.js'></script> 注意这三个js文件顺序不能颠倒<script type='text/javascript' src='/test_dwr/dwr/util.js'></script> <script type='text/javascript' src='/test_dwr/dwr/interface/service.js'></script> <script type="text/javascript"> function hello(){ service.sayHello("Meng Wei", callback); } function callback(data){ alert(data); } </script> </head> <body><input type="button" value="OK" οnclick="hello()" /> </body> </html>