DWR2一大特性就是在DWR中可以通路WEB上下文的SERVLET,REQUEST等,主要用到的類是WebContext,WebContextFactory,使用WebContextFacotry.get()方法得到目前的WebContext,原理是将WebContext與目前thread綁定,内部使用ThreadLocal來維護。
use case:
在IE中使用JAVASCRIPT來判斷制定使用者名經是否已經登陸。
client(index.jsp)
<% @ page language = " java " import = " java.util.* " pageEncoding = " gb2312 " %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + " :// " + request.getServerName() + " : " + request.getServerPort() + path + " / " ;
// 為示範:假設已經登入成功
request.getSession( true ).setAttribute( " cur_user " , " jack " );
%>
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " >
< html >
< head >
< base href = " <%=basePath%> " >
< 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/UserCheck.js ' > </ script >
< script language = " javascript " >
function checkUserIsLogin(name) ... {
UserCheck.checkUserIsLogin(name,function(res) ...{
var retMsg = ( true == res ) ? "已經登入" : "未登入";
DWRUtil.setValue("msg",retMsg);
}
);
}
</ script >
</ head >
< body >
< input type = " text " name = " username " />< input type = " button " value = " check " onclick = " checkUserIsLogin(document.all.username.value) " /> 目前session中儲存為jack
< br />
< div id = " msg " ></ div >
</ body >
</ html >
服務端:UserCheckUtil.java
package com.dwr;
import javax.servlet.http.HttpSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
public class UserCheckUtil ... {
public boolean checkUserIsLogin(String username) ...{
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession(false);
if (null != session && username.equals(String.valueOf(session.getAttribute("cur_user"))))
return true;
else
return false;
}
}
配置檔案:dwr.xml
<? 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 >
< allow >
< create creator ="new" javascript ="UserCheck" >
< param name ="class" value ="com.dwr.UserCheckUtil" />
</ create >
</ allow >
</ dwr >