struts2 拦截器的使用

本文详细介绍了如何使用拦截器实现登录验证功能,并在Struts配置文件中配置拦截器,确保每个Action都能正确调用。

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

自己学习的一点知识的总结!!

(1)先写一个拦截器的类

package com.vrv.nj.cims.action;


import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;


public class CheckLoginInterceptor extends AbstractInterceptor {
    /**

*/
    private static final long serialVersionUID = 1L;
    public static final String LOGIN_KEY = "username";(session中的key值)
    public static final String LOGIN_PAGE = "userLogin.jsp";登录的的页面
 
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
 
        System.out.println("begin check login interceptor!");
        // 对LoginAction不做该项拦截
        Object action = actionInvocation.getAction();
        if (action instanceof LoginAction) {
            System.out.println("exit check login, because this is login action.");
            return actionInvocation.invoke();
        }
        // 确认Session中是否存在LOGIN
        Map session = actionInvocation.getInvocationContext().getSession();
        String login = (String) session.get(LOGIN_KEY);
        if (login != null && login.length() > 0) {
            // 存在的情况下进行后续操作。
            System.out.println("already login!");
            return actionInvocation.invoke();
        } else {
            // 否则终止后续操作,返回LOGIN
            System.out.println("no login, forward login page!");
            return  Action.LOGIN;
        }
    }

}

(2)在struts.xml配置文件中配置拦截器

    <!-- 拦截器必须要定义在action的上面 -->
<!-- 配置拦截器 -->
<interceptors>
<!-- 定义拦截器 -->
<interceptor name="loginInterceptor"
class="com.vrv.nj.cims.action.CheckLoginInterceptor" />
<!-- 定义成默认的拦截器每个action都能用 -->
<interceptor-stack name="teamwareStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>


<default-interceptor-ref name="teamwareStack" />

<!-- 定义全局Result -->  
        <global-results>  
            <!-- 当返回login视图名时,转入/login.jsp页面 -->  
            <result name="login">/userLogin.jsp</result>  
        </global-results> 


        <action name="loginAction" class="com.vrv.nj.cims.action.LoginAction">
<result name="loginFail">/userLogin.jsp</result>
<result name="loginSuccess" type="redirectAction">contextList!getAllContext</result>
<result name="outSuccess">/userLogin.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值