配置DWR的時候,先拷貝如下servlet到web.xml設定檔中:
<!-- dwr ajax 配置 --> <servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>WEB-INF/dwr.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>scriptCompressed</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
添加FITLER:
<!-- dwr fitler --> <servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
配置dwr.xml檔案,可以直接使用spring管理的bean:
<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd">
<dwr>
<allow>
<!-- 自己定義的BEAN,所以要轉化一下,不然不認識 -->
<convert match="com.sillycat.core.model.User" converter="bean" />
<!-- 大寫的UserManager是頁面上調用的JS的名字 -->
<create creator="spring" javascript="UserManager">
<!-- 小寫userManager是spring管理的BEAN的名字 -->
<param name="beanName" value="userManager" />
<!-- ajax暴露的方法,應該只暴露一些安全的方法。。。 -->
<include method="getAllUser" />
<include method="getUser" />
<include method="saveUser" />
<include method="removeUser" />
</create>
</allow>
</dwr>
頁面在使用時,匯入三個JS檔案: <script type='text/javascript'
src='<%=request.getContextPath()%>/dwr/interface/UserManager.js'></script>
<script type='text/javascript'
src='<%=request.getContextPath()%>/dwr/engine.js'></script>
<script type='text/javascript'
src='<%=request.getContextPath()%>/dwr/util.js'></script>
頁面上的JS:function checkUserExist()...{
if($("logonName").value == null || $("logonName").value == "")...{
loginNameMessage.innerHTML="請輸入登陸名!";
return false;
}
DWRUtil.useLoadingMessage("checking .....");
UserManager.isTUserExistByLogonName(userCheckResult,$("logonName").value);
}
function userCheckResult(data)...{
if(data == true)...{
//alert("adsfasdfasdf");
document.getElementById("userExistFlag").value = 1;
loginNameMessage.innerHTML="使用者名稱已經被使用!";
}else...{
alert("adsfasdf");
loginNameMessage.innerHTML="";
document.getElementById("userExistFlag").value = "0";
}
}
調用AJAX的JS是:
UserManager.isTUserExistByLogonName(userCheckResult,$("logonName").value);
UserManager就是JS的名字,第一個參數是回呼函數,後一個參數是調用的方法的參數