session 超时处理

本文介绍了如何在使用Acegi安全框架时,处理Ajax远程调用导致的session超时问题,确保用户在进行登录验证时能够顺利跳转到登录页面。通过配置Acegi安全框架允许特定路径的匿名访问、自定义DWRRemoter以及调整web.xml文件,实现了在session超时后,Ajax请求能够正确地引导用户至登录页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们使用Acegi安全框架时,一般都会对所有请求就像拦截。这样,如果session超时,通过DWR进行Ajax远程调用时,同样会被Acegi的Filter拦截,这时Acegi发现用户没有登录,就会对请求进行转发(转发到登录页面),但由于此时进行的是Ajax的调用,页面并不会将进行跳转,而是返回302的HTTP响应码,这样浏览器就不会有任何的反应,这样对用户是非常不友好的。可以通过一些简单的处理,在session超时后,当用户进行Ajax远程调用时,同其他请求一样,返回到登录页面。

首先,在Acegi的安全配置文件(即Spring的配置文件)里面,将/dwr/**路径的请求配置为可以匿名用户可以访问的。

其次,自定义一个DWRRemoter,大概实现如下:

Java代码
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 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()"));
}
}

在web.xml文件中加入DWR的参数,是自定义的DWRRemoter生效:

Xml代码
<init-param>
<param-name>
org.directwebremoting.extend.Remoter
</param-name>
<param-value>com.xxx.base.framework.web.MyDWRRemoter</param-value>
</init-param>

<init-param>
<param-name>
org.directwebremoting.extend.Remoter
</param-name>
<param-value>com.xxx.base.framework.web.MyDWRRemoter</param-value>
</init-param>

最后,在JSP页面上写下方法名为logOut的JavaScript函数,该函数返回到登录页面即可。



通过上面的三个简单步骤,即可实现在DWR调用远程方法时,如果session超时,系统顺利的退出到登录页面的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值