用Struts2的拦截器验证用户是否登录

   用户的登录验证是一个应用很普遍的功能,Struts2的拦截器可以很好的实现它,具体步骤如下:

    1,首先建立一个自定义的拦截器----********Interceptor,它直接继承com.opensymphony.xwork2.interceptor.AbstractInterceptor类,并覆盖其的intercept()方法。这个方法有个ActionInvocation类型的参数,可以用它取得Session或进行转发请求等操作。

    2,在struts.xml中对自定义的拦截器进行配置,并重定义默认拦截器堆栈

    3,添加一个global-results,用户在验证失败的情况下跳转到登陆验证页面

 

下面是一个完整的示例,登录的action为loginAction,他可以直接被拦截器过滤掉,

   

public classAuthorizationInterceptor extends AbstractInterceptor

{

privateString ignoreActions;

 

//ignoreActions属性的getter方法

publicString getIgnoreActios()

{

returnignoreActions;

}

 

//ignoreActions属性的setter方法

publicvoid setIgnoreActions(String ignoreActions)

{

this.ignoreActions= ignoreActions;

}

 

@Override

publicString intercept(ActionInvocation invocation) throws Exception

{

ActionContextctx = invocation.getInvocationContext();

 Mapsession = ctx.getSession();

Stringuser = (String) session.get("username");

 

booleanignore = false;

StringcurrentAction = invocation.getProxy().getActionName();

String[]actions = ignoreActions.split(",");

 

for(String action : actions){

if(currentAction.matches(action.trim())){

ignore= true;

break;

}

}

 

if(user != null || ignore == true){

 returninvocation.invoke();

}else{

returnAction.LOGIN;

}

 }

}

 2,配置文件需要添加的部分代码如下:

     

<interceptors>

<interceptorname="authorization"

class="interceptor.AuthorizationInterceptor"/>

<interceptor-stackname="myStack">

<interceptor-refname="authorization">

<paramname="ignoreActions">

.*login.*

</param>

</interceptor-ref>

<interceptor-refname="defaultStack" />

</interceptor-stack>

</interceptors>

<default-interceptor-refname="myStack" />

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值