前几天由于项目的需要专门研究了下DWR,虽然网上的资料不是很多,但官方文档写得很好。发现他的简单,实用,作为AJAX框架,它让我大为兴奋
1、传对象到前台浏览器
首先说下基本的配置,需要的jar包
web.xml配置
<servlet>
<display-name>DWR Servlet</display-name>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<!-- 配置调试模式,可以在localhost:8080/XiongFeng/dwr/看到js脚本化的类,若没有加上,访问 localhost:8080/XiongFeng/dwr/会包error错误-->
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
dwr.xml配置
<create creator="new" javascript="UserService">
<param name="class" value="com.dwr.service.UserService"/>
</create>
//若要传对象,需要下面的配置,这样就直接可以把对象传到浏览器前台了
<convert converter="bean" match="com.dwr.model.User"/>
java代码
User 类
package com.dwr.model;
public class User {
int id ;
String name ;
int number ;
public User(){}
public User(int id,String name,int number) {
super();
this.id = id;
this.name = name;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "id="+id+" name="+name+" number="+number;
}
}
UserService类
public class UserService {
public User loadUser(){
User user = new User(1,"张三",1);
return user ;
}
}
jsp代码
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!--要加上必要的dwr引擎,还有顺序不能颠倒-->
<Meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<script src='<%=request.getContextPath() %>/dwr/engine.js'></script>
<script src='<%=request.getContextPath() %>/dwr/interface/UserService.js'></script>
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
window.onload=function(){
//返回一个带有返回值function函数
UserService.loadUser(result);
};
function result(user){
alert(user.number+","+user.name+",");
}
</script>
</body>
</html>
看到这里,运行之后,惊奇发现把对象传到前台来了