最近在做项目是用到DWR,在网上查了好多相关资料,最后将自己在项目中的运用过程总结一下,以供以后进一步学习之用。
1.在web.xml中配置dwrservlet,如下:
<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>false</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>
2.配置dwr.xml配置文件,告诉dwr都可以访问那些java类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<!-- dwr方法 -->
<create javascript="dwrSrv" creator="spring">或者
<create javascript="dwrSrv" creator="new">或者 // dwrSrv是js访问java是的引用名称,creator说明如何得到java类实例,param告诉dwr可以访问的java类,include中指明可以访问的方法,conver指明js和java类直接的属性类型转换
<param name="beanName" value="DwrFactoryImpl" />
<include method="RoleCheck" />
<include method="getAccountList"/>
<include method="generateBusinessData"/>
<include method="getRoleType"/>
<!-- 验证码校验 -->
<include method="imageValidate"/>
</create>
<convert match="com..po.Area" converter="bean"></convert>
</allow>
</dwr>
3.编写java类
public Map getItem(String no) {
OperationImpl opt = new OperationImpl();
Map<String, String> dwrmap = new HashMap<String, String>();
try {
List list = opt.queryObjectList("select o from Item o where o.no='"+no+"' order by o.no");
for (int i = 0; i < list.size(); i++) {
Item item = (Item)list.get(i);
dwrmap.put(item.getNo(), item.getItemNo()+"|"+item.getItemName());
}
} catch (AppRuntimeException e) {
return null;
}
return dwrmap;
}
4.js引用
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<link href="/pages/style/common.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="/dwr/engine.js"></script>
<script language="javascript" src="/dwr/util.js"></script>
<script language="javascript" src="/dwr/interface/dwrSrv.js"></script> //dwrSrv.js是dwr根据配置文件生成的js文件。
<html:base/>
</head>
<script type="text/javascript">
function getItem() {
var no = document.getElementById("no").value;
dwrSrv.getFundItem(no,setValue);
}
function setValue(obj) {
var trd = document.getElementById("itemNO");
dwr.util.removeAllOptions(trd);
dwr.util.addOptions(trd,{'':'请选择'});
dwr.util.addOptions(trd,obj);
}
</script>