dwr是方便使用ajax连接js和java的一个框架,把服务器端的java对象的方法公开给javascript代码。(是ajax的开源框架)
dwr要在web.xml文件件中配置,也有自己的配置文件dwr.xml,调用javabean。
使用方法:
1,导入dwr.jar,commons-logging.jar,log4.jar.
2,配置web.xml。
web.xml:
<?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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
下面是dwr的配置信息:
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>crossDomainSessionSecurity</param-name>
<param-value>false</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
3,写服务器端的代码:(javabean)
4,配置dwr.xml:
<?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.xml的头文件很重要。
<dwr>
<allow>
<create creator="new" javascript="Hello"> //javabean的方法。
<param name="class" value="org.wll.www.bean.Hello" />//这里与javabean的包相对应。
</create>
</allow>
</dwr>
再就是web页面的调用。
<html>
<head>
<base href="<%=basePath%>">
<title>dwr实例</title>
<script type='text/javascript' src='/TestDwr/dwr/interface/Hello.js'></script>
<script type='text/javascript' src='/TestDwr/dwr/engine.js'></script>
<script type='text/javascript' src='/TestDwr/dwr/util.js'></script>
<script type='text/javascript' src='hello.js'></script>//这个js是自己写得一个方法。(下面有 hello.js)
</head>
<body>
<input id="user" type="text" />
<input type='button' value='你好' onclick='hello();'/>
<div id="result"></div>
</body>
</html>
hello.js:
function hello(){
var user = $('user').value;
Hello.checks(user, callback);
}
function callback(msg){
if (typeof window['DWRUtil'] == 'undefined')
{
window.DWRUtil = dwr.util;
}
DWRUtil.setValue('result', msg);
}