dwr 简单实例
今天学习了一下dwr,做一个简单的总结:
将写一个的简单的实例:
首先在网上下载一个dwr.jar,commons-logging.jar这个两个jar包,放到工程的lib目录中:
然后开始写代码了:
这个是我的服务层的代码:
public class HelloWorld {public String sayHello(String name) { return "Hi, " + name; }
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><!-- DWR配置 --><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><!--解决 dwr 报session error 问题 --><init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param><init-param> <!--主要是为了指定dwr.xml文件所在的位置 --><param-name>config</param-name><param-value> /WEB-INF/dwr/dwr.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>dwr-invoker</servlet-name><url-pattern>/dwr/*</url-pattern></servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd"><dwr><allow><create creator="new" javascript="sayHelloTo"><param name="class" value="com.me.dwr.HelloWorld" /><include method="sayHello" /></create></allow></dwr>
<%@ page language="java" pageEncoding="gbk"%><html><head><title>Dwr 调用测试</title><!--这里sayHelloTo.js 是通过dwr.xml中配置的create标签中javascript配置的值是一致的 --><script src='dwr/interface/sayHelloTo.js'></script><script src='dwr/engine.js'></script><script src='dwr/util.js'></script><script type="text/javascript"> function btn_onClick(){ var username = document.myform.name.value; //调用dwr.xml中配置的类方法,回调函数callback带有返回的结果集 sayHelloTo.sayHello(username,callback); } function callback(data){ document.getElementById("info").innerText=data; } </script></head><body><form name="myform" method="post"><input type="text" id="name" name="name" /><input type="button" value="sayHello" onclick="btn_onClick()" /><div id="info"></div></form></body></html>