dwr框架的使用
dwr是一个ajax框架,在js代码就可以很轻松调用java类的方法,dwr和ajax有什么区别,dwr配置比较多,js写的代码比较少,ajax不需要什么配置,写的代码比较多
怎么使用dwr框架呢?
先下载dwr30.jar,common-logging.jar,放在lib下面
在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">
<param name="class" value="com.chen.Chen"></param>
</create>
</allow>
</dwr>
creator 用new的方式创建,javaScript表示在js页面用的标识符调用java的函数,param标签指定标识符调用的类
web.xml中的配置为
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>dwr-invoke</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!-- 配置dwr的debug功能方便测试,发布的时候记得一定删除 --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoke</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
java类
package com.chen; public class Chen { public String getName(String name){ System.out.println("a"); return name + "abc"; } }
页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type='text/javascript' src='dwr/interface/DWRService.js'></script> <script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script> var callServiceMethod = function(obj){ // 参数1是需要给 java类方法的参数 //最后的参数是 回调方法 DWRService.getName('abc',function(data){ alert("b") alert(data); }); }; callServiceMethod(); </script> </head> <body> abc </body> </html>