我在做公司某个框架时有这么一个需求。每次调用dwr的方法前要检查用户是否已经登录,否则就不能执行并且退到首页。
当然了,做拦截器有很多方式,但经过研究发现DWR自带很多插件,其中就有一个调用处理的插件。具体做法如下。
在web.xml里的DWR配置中加入一个参数:
然后自己创建这个实现类。
其中,检查用户是否登录,如果没有登录就返回一个空的super.execute( new Calls());, 不能返回null否则会报错。
检查通过就调用super.execute( calls ); 其实calls里还能获得很多信息。
最后大家注意logOut方法,这里用到了DWR2.0新功能:DWR反向调用,就是DWR调用javascript,具体用法大家网上可以查到,需要配置的,我这里就不多说了。补充一下,addScript调用的是html里的function logOut().
这样的话,如果用户session超时,或被管理员踢掉,一旦他做任何dwr操作就会被强迫登出到首页了。
当然了,做拦截器有很多方式,但经过研究发现DWR自带很多插件,其中就有一个调用处理的插件。具体做法如下。
在web.xml里的DWR配置中加入一个参数:
<
init-param
>
< param-name >
org.directwebremoting.extend.Remoter
</ param-name >
< param-value > com.xxx.base.framework.web.MyDWRRemoter </ param-value >
</ init-param >
< param-name >
org.directwebremoting.extend.Remoter
</ param-name >
< param-value > com.xxx.base.framework.web.MyDWRRemoter </ param-value >
</ init-param >
然后自己创建这个实现类。
public
class
MyDWRRemoter
extends
DefaultRemoter
{
public Replies execute( Calls calls )
{
HttpSession session = WebContextFactory.get().getSession();
ISessionContainer sc = ( ISessionContainer ) session.getAttribute( ISessionContainer.SESSION_CONTAINER_KEY );
//session检查
if ( sc == null || sc.getUserInfo() == null )
{
logOut();
return super.execute( new Calls() );
}
else
{
IUserInfo userInfo = sc.getUserInfo();
if(!SecurityFactory.getInstance().isOnline( userInfo.getUserID(), session.getId() ))
{
logOut();
return super.execute( new Calls() );
}
}
return super.execute( calls );
}
private void logOut()
{
WebContext wct = WebContextFactory.get();
Util utilThis = new Util(wct.getScriptSession());
utilThis.addScript( new ScriptBuffer("logOut()"));
}
}
{
public Replies execute( Calls calls )
{
HttpSession session = WebContextFactory.get().getSession();
ISessionContainer sc = ( ISessionContainer ) session.getAttribute( ISessionContainer.SESSION_CONTAINER_KEY );
//session检查
if ( sc == null || sc.getUserInfo() == null )
{
logOut();
return super.execute( new Calls() );
}
else
{
IUserInfo userInfo = sc.getUserInfo();
if(!SecurityFactory.getInstance().isOnline( userInfo.getUserID(), session.getId() ))
{
logOut();
return super.execute( new Calls() );
}
}
return super.execute( calls );
}
private void logOut()
{
WebContext wct = WebContextFactory.get();
Util utilThis = new Util(wct.getScriptSession());
utilThis.addScript( new ScriptBuffer("logOut()"));
}
}
其中,检查用户是否登录,如果没有登录就返回一个空的super.execute( new Calls());, 不能返回null否则会报错。
检查通过就调用super.execute( calls ); 其实calls里还能获得很多信息。
最后大家注意logOut方法,这里用到了DWR2.0新功能:DWR反向调用,就是DWR调用javascript,具体用法大家网上可以查到,需要配置的,我这里就不多说了。补充一下,addScript调用的是html里的function logOut().
这样的话,如果用户session超时,或被管理员踢掉,一旦他做任何dwr操作就会被强迫登出到首页了。