1、第一步下载dwr.jar包(百度dwr下载即可,不赘述!)
2、新建Dynamic Web Project ,将dwr.jar包拷贝到WEB-INF/lib路径目录下,其实要完整的更好的使用dwr.jar,建议下载dwr.war包,解压后,可以得到案例的lib下的一些
jar文件,比较全!
3、编写web.xml文件
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems,Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app id="dwr"> <listener> <listener-class>org.directwebremoting.servlet.DwrListener</listener-class> </listener> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <span> </span><init-param> <span> </span><param-name>fileUploadMaxBytes</param-name> <span> </span><param-value>25000</param-value> </init-param> <init-param> <span> </span><param-name>debug</param-name> <span> </span><param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> </web-app> </span>4、编写相应的java类
</pre><pre name="code" class="java"><span style="font-size:18px;">package com.hzg.util; public class Hello { public String hello(String name) { return name+"欢迎你!"; } } </span>
5、在dwr.xml文件中配置javascript需要访问的java类和方法
<span style="font-size:18px;"><?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="Hello" scope="application"> <param name="class" value="com.hzg.util.Hello"></param> </create> <!-- <convert match="com.hzg.util.Hello" converter="bean"></convert> --> </allow> </dwr> </span>
6、HTML网页
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <Meta charset="utf-8"> <title></title> <script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script type='text/javascript' src='dwr/interface/Hello.js'></script> <script type="text/javascript"> window.onload = function(){ $("show").onclick = function(){ var name = $("name").value; Hello.hello(name,function (data){ $("content").innerHTML+=data; }); }; }; </script> </head> <body> <input id="name" type="text"><input type="button" id="show" value="使用DWR"> <div id="content" style="border:1px solid #ccc;width: 300px;height: 100px" ></div> </body> </html></span>
7、效果
原文链接:https://www.f2er.com/ajax/164356.html