DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站.它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。
以下模拟一个简单的dwr入门案例,重点理解dwr是如何跟java后台服务器打交道的
模拟效果如下
模拟从服务器加载下拉列表数据
模拟保存功能
接下来为dwr+spring集成步骤:
1、新建一个web工程,导入dwr+spring所需jar,如下图
目录结构图
修改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"> <!-- Spring上下文 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resource/app*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置DWR前端控制器 --> <servlet> <servlet-name>dwrServlet</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!-- 指定配置文件 --> <init-param> <param-name>config</param-name> <!-- 如果有多个用","分开 --> <param-value> /WEB-INF/classes/config/dwr.xml </param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwrServlet</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> </web-app>
新建实体类Dept
package entity; public class Dept { private Long id; private String name; public Dept() { } public Dept(Long id,String name) { this.id = id; this.name = name; } public Long getId() { return id; } void setId(Long id) { this.id = id; } public String getName() { return name; } void setName(String name) { this.name = name; } }
新建业务逻辑类
DeptServices类
package services; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import entity.Dept; @SuppressWarnings("unchecked") class DeptServices { public List findDept() { throw new RuntimeException("查找失败!"); } 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; } 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 = try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return depts; } }
HelloServices类
/** * @author dlwu * */ class HelloServices { public String sayHello(String name){ System.out.println("Hello now!"); return "Hello " + name + "!"; } }
LoginService类
import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; class LoginService { void checkUserLogin(String userid,String pwd){ WebContext ctx = WebContextFactory.get(); ctx.getSession().setAttribute("userid",userid); } public String getLoginUser(){ WebContext ctx = WebContextFactory.get(); return (String)ctx.getSession().getAttribute("userid"); } }
配置applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" > <bean id="deptServices" class="services.DeptServices"></bean> <bean id="loginSrv" class="services.LoginService"></bean> </beans>
配置dwr.xml,dwr.xml是前台js跟java服务器沟通的桥梁
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd"> <!-- 通用dwr配置 --> <dwr> <allow> <!-- 建立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>
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"> </head> <!-- 记得引入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,0)"> } </script> <body> <div id="msg"></div> <input type="text" id="name" /> <input type="button" value="Hello" onclick="hello();" /> </body> </html>
dept.jsp页面
<%@ page language="java" Meta http-equiv="description" content="This is my page">
</head>
<!-- 记得引入js,测试地址: http:
<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 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,'name');
});
}
function loadDept2(){
if($('depts2').options.length > 0){
return;
}
DWRUtil.addOptions('depts2','getDeptsForPo',function(depts){
DWRUtil.removeAllOptions('depts2');
DWRUtil.addOptions('depts2','name');
});
}
function saveDept(){
声明dept对象 var dept = {
id:$("deptid").value,name:$("deptname").value
};
dwr.engine._execute("dwr",'saveDept',[dept],function(){
alert('保存成功!');
});
}
function find(){
dwr.engine._execute("dwr",'findDept',{
callback:function(results){
alert('查询成功!');
},errorHandler:function(e){
alert("查询失败:" + e);
}
});
}
</script>
<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>