版权声明:有问题可以大家一起交流学习! https://blog.csdn.net/laonayonghaifeisi/article/details/52145368
DWR(Direct Web Remoting)是一个WEB远程调用框架.利用这个框架可以让AJAX开发变得很简单.利用DWR可以在客户端利用JavaScript直接调用服务端的Java方法并返回值给JavaScript就好像直接本地客户端调用一样(DWR根据Java类来动态生成JavaScrip代码).它的最新版本DWR0.6添加许多特性如:支持Dom Trees的自动配置,支持Spring(JavaScript远程调用spring bean),更好浏览器支持,还支持一个可选的commons-logging日记操作.
其大概开发过程如下:
1.编写业务代码,该代码是和dwr无关的。
2.确认业务代码中哪些类、哪些方法是要由javascript直接访问的。
3.编写dwr组件,对步骤2的方法进行封装。
4.配置dwr组件到dwr.xml文件中,如果有必要,配置convert,进行java和javascript类型互转。
5.通过反射机制,dwr将步骤4的类转换成javascript代码,提供给前台页面调用。
5.编写网页,调用步骤5的javascript中的相关方法(间接调用服务器端的相关类的方法),执行业务逻辑,将执行结果利用回调函数返回。
6.在回调函数中,得到执行结果后,可以继续编写业务逻辑的相关javascript代码。
本次例子只是用于演示,说明DWR的使用,类设计并不是最优的
注意事项:需要引入js文件
<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/helloSrv.js"></script>
<script type="text/javascript" src="dwr/engine.js"></script>
dwr自动生成文件 有的版本需要放在js文件中引入【有的会自动生成,根据版本而定】
<script type="text/javascript" src="dwr/util.js"></script>
dwr自动生成文件 有的版本需要放在js文件中引入【有的会自动生成,根据版本而定】
<script type="text/javascript" src="dwr/interface/helloSrv.js"></script>
你自定义的dwr中JavaScript对象名称
例如:
<!-- 建立JS对象,将目标对象的方法转换成JS对象的方法 -->
<create javascript="helloSrv" creator="new">
<param name="class" value="services.HelloServices"></param>
</create>
测试时候可以使用:{调试}
http://localhost:8082/WebSpringDWR/dwr/index.html
项目路径/dwr/index.html 查看详细的dwr生成的信息 可以帮助调试
DWR调用方法
<script type="text/javascript">
function hello() {
//方法一
//返回处理后的结果信息
/*var fn = function(result){
$("msg").innerHTML = result;
}
helloSrv.sayHello($("name").value, fn);*/
//方法二
helloSrv.sayHello($("name").value, function (result) {
$("msg").innerHTML = result;
});
//方法三
//使用如下的好处为:不用导入如上三个js
//第一个参数: dwr访问路径,在web.xml中配置,如: <url-pattern>/dwr/*</url-pattern>
//第二个参数: dwr与java服务器通信变量,在dwr.xml中声明
//第三个参数: 服务器方法名
//第四个参数: 页面请求参数,即服务器方法名得参数
//第五个参数: 回调函数
//dwr.engine._execute("dwr", 'helloSrv', 'sayHello', $("name").value, fn);
}
</script>
依赖jar包
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="spring" javascript="tanqingming">
<param name="beanName" value="tanQingMingService"/>
</create>
<create creator="spring" javascript="hello01">
<param name="beanName" value="helloTianMingService"/>
</create>
<!-- 建立JS对象,将目标对象的方法转换成JS对象的方法 -->
<create javascript="helloSrv" creator="new">
<param name="class" value="services.HelloServices"></param>
</create>
<!-- 从Spring中获取Java对象 -->
<create javascript="deptSrv" creator="spring">
<param name="beanName" value="deptServices"></param>
<!-- 禁止执行 -->
<exclude method="deleteDept" />
</create>
<create javascript="loginSrv" creator="spring">
<param name="beanName" value="loginSrv"></param>
</create>
<!-- 指定针对于特定对象的转换器 -->
<convert match="entity.*" converter="bean"></convert>
<convert match="java.lang.Throwable" converter="bean">
<param name="include" value="message"></param>
</convert>
</allow>
</dwr>
**
spring配置文件beans.xml
**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 打开Spring的Annotation支持 -->
<context:annotation-config />
<!-- 设定Spring 去哪些包中找Annotation -->
<context:component-scan base-package="com.lessony.dwr.spring01,services" />
<!--注入bean内容-->
<bean id="deptServices" class="services.DeptServices"></bean>
<bean id="loginSrv" class="services.LoginService"></bean>
</beans>
**
web.xml 配置文件
**
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 创建Spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring 的监听器可以通过这个上下文参数来获取beans.xml的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--以下是dwr配置-->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<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>
<init-param>
<param-name>allowScriptTagRemoting</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>
</web-app>
Java代码简单helloword实现:
package services;
/**
* @author dlwu
*
*/
public class HelloServices {
public String sayHello(String name) {
System.out.println("Hello now! tianming");
return "Hello " + name + " tianming !";
}
}
基于springmvc的注解方式实现:
package com.lessony.dwr.spring01.service.impl;
import com.lessony.dwr.spring01.service.IHelloService;
import org.springframework.stereotype.Service;
@Service("helloTianMingService")
public class HelloTianMingService implements IHelloService {
@Override
public String sayHello(String name) {
System.out.println("hello " + name);
return "hello tanqingming : "+name;
}
}
**
hello.jsp 实现
**
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'hello.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- 记得引入js,测试地址: http://localhost:8083/dwrweb/dwr/ -->
<script type="text/javascript" src="dwr/engine.js"></script>
<script type="text/javascript" src="dwr/interface/helloSrv.js"></script>
<script type="text/javascript" src="dwr/util.js"></script>
<script type="text/javascript">
function hello() {
//方法一
//返回处理后的结果信息
/*var fn = function(result){
$("msg").innerHTML = result;
}
helloSrv.sayHello($("name").value, fn);*/
//方法二
helloSrv.sayHello($("name").value, function (result) {
$("msg").innerHTML = result;
});
//方法三
//使用如下的好处为:不用导入如上三个js
//第一个参数: dwr访问路径,在web.xml中配置,如: <url-pattern>/dwr/*</url-pattern>
//第二个参数: dwr与java服务器通信变量,在dwr.xml中声明
//第三个参数: 服务器方法名
//第四个参数: 页面请求参数,即服务器方法名得参数
//第五个参数: 回调函数
//dwr.engine._execute("dwr", 'helloSrv', 'sayHello', $("name").value, fn);
}
</script>
</head>
<body>
<div id="msg"></div>
<input type="text" id="name" />
<input type="button" value="Hello" onclick="hello();" />
</body>
</html>
部门下拉列表实现
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'hello.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- 记得引入js,测试地址: http://localhost:8083/dwrweb/dwr/ -->
<script type="text/javascript" src="dwr/engine.js"></script>
<script type="text/javascript" src="dwr/interface/loginSrv.js"></script>
<script type="text/javascript" src="dwr/interface/helloSrv.js"></script>
<script type="text/javascript" src="dwr/interface/deptSrv.js"></script>
<script type="text/javascript" src="dwr/interface/hello01.js"></script>
<script type="text/javascript" src="dwr/util.js"></script>
<script type="text/javascript">
function loadDept() {
//说明已经加载,不必重新加载
if ($('depts').options.length > 0) {
return;
}
DWRUtil.addOptions('depts', [{id: '', name: '正在下载...'}], 'id', 'name');
dwr.engine._execute("dwr", 'deptSrv', 'getDepts', function (depts) {
DWRUtil.removeAllOptions('depts');
DWRUtil.addOptions('depts', depts, 'id', 'name');
});
}
function loadDept2() {
if ($('depts2').options.length > 0) {
return;
}
DWRUtil.addOptions('depts2', [{id: '', name: '正在下载...'}], 'id', 'name');
dwr.engine._execute("dwr", 'deptSrv', 'getDeptsForPo', function (depts) {
DWRUtil.removeAllOptions('depts2');
DWRUtil.addOptions('depts2', depts, 'id', 'name');
});
}
function saveDept() {
//声明dept对象
var dept = {
id: $("deptid").value,
name: $("deptname").value
};
dwr.engine._execute("dwr", 'deptSrv', 'saveDept', [dept], function () {
alert('保存成功!');
});
}
function find() {
dwr.engine._execute("dwr", 'deptSrv', 'findDept', {
callback: function (results) {
alert('查询成功!');
},
errorHandler: function (e) {
alert("查询失败:" + e);
}
});
}
</script>
</head>
<body>
<select id="depts" onclick="loadDept();"></select>
<select id="depts2" onclick="loadDept2();"></select>
<hr/>
ID:<input id="deptid" type="text" size="8"/>
Name:<input id="deptname" type="text" size="8"/>
<input value="保存部门" type="button" onclick="saveDept();"/>
<input value="查找" type="button" onclick="find();"/>
</body>
</html>
Java代码DeptServices 实现:
package services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import entity.Dept;
@SuppressWarnings("unchecked")
public class DeptServices {
public List findDept() {
throw new RuntimeException("查找失败!");
}
public void deleteDept(Long id) {
System.out.println("Delete dept " + id);
}
public List getDeptsForPo() {
List depts = new ArrayList();
depts.add(new Dept(1l, "教质部"));
depts.add(new Dept(2l, "学术部"));
depts.add(new Dept(3l, "就业部"));
depts.add(new Dept(4l, "咨询部"));
return depts;
}
public void saveDept(List<Dept> depts) {
// System.out.println(dept.getId() + ":" + dept.getName());
System.out.println(depts);
}
public List getDepts() {
List depts = new ArrayList();
Map map = new HashMap();
map.put("id", "01");
map.put("name", "教质部");
depts.add(map);
map = new HashMap();
map.put("id", "02");
map.put("name", "学术部");
depts.add(map);
map = new HashMap();
map.put("id", "03");
map.put("name", "就业部");
depts.add(map);
map = new HashMap();
map.put("id", "04");
map.put("name", "咨询部");
depts.add(map);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return depts;
}
}
实现效果图