如何编写 AuthenticationInterceptor 验证 Session 中的 user 对象?

解读

在国内企业级 Java Web 面试中,**“自定义拦截器做登录态校验”**是高频考点。
面试官想确认:

  1. 你是否真正理解 Struts2 拦截器生命周期(init→intercept→destroy)。
  2. 能否正确、线程安全地 读取 Session 并做 跳转/放行 决策。
  3. 是否具备 细粒度排除路径(如 /login、/captcha)的工程意识,避免“一刀切”把静态资源也拦掉。
  4. 是否熟悉 Struts2 常量覆盖(如 struts.action.excludePattern)与 XML/注解两种注册方式,以匹配公司现有代码基线。

答得太浅(只写一行 if(session.get("user")==null))会被认为“玩具代码”;答得太深(把 Spring Security 整套搬进来)又会被嫌“过度设计”。因此,给出可直接落地的模板代码 + 配置细节 + 可扩展接口,最能打动面试官。

知识点

  1. Struts2 核心入口:请求先经过 StrutsPrepareAndExecuteFilter,再进入 拦截器栈;自定义拦截器必须实现 com.opensymphony.xwork2.interceptor.Interceptor 或继承 AbstractInterceptor。
  2. Session 获取:Struts2 使用 ActionContext#getSession(),返回 Map<String,Object>,屏蔽了底层 HttpSession,便于单元测试。
  3. 线程安全:ActionContext 与当前线程绑定,禁止在拦截器里声明实例变量保存状态。
  4. 结果码常量:Action.LOGIN(值为 “login”)是 Struts2 预定义,可直接复用,保持与全局结果<result name="login">/login.jsp</result>一致。
  5. 路径排除:
    • XML 方式:在 struts.xml 中给拦截器栈加 <interceptor-ref name="defaultStack"> 并配置 <param name="excludeMethods">input,back,cancel</param>,仅对方法生效。
    • URL 方式:使用 struts.action.excludePattern 正则排除 /login,/static/* 等。
  6. 与 Spring 集成:若用户 Service 由 Spring 管理,拦截器也可被 Spring 托管(class 由 Spring 创建),可直接 @Autowired 依赖。
  7. 性能注意:拦截器里 禁止远程调用(如 RPC 查库),只做内存级断言;需要刷新登录态应放在 业务线程或异步消息。

答案

  1. 创建 AuthenticationInterceptor.java
package cn.xxx.interceptor;

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

public class AuthenticationInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = 1L;

    // 允许匿名访问的 Action 名,支持通配符
    private String excludeActions;
    public void setExcludeActions(String excludeActions) {
        this.excludeActions = excludeActions;
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ctx = invocation.getInvocationContext();
        Map<String, Object> session = ctx.getSession();

        // 1. 先判断当前命名空间 + Action 名是否在白名单
        String namespace = invocation.getProxy().getNamespace();
        String actionName = invocation.getProxy().getActionName();
        String uri = namespace + "/" + actionName;
        if (excludeActions != null && uri.matches(excludeActions.replace("*", ".*"))) {
            return invocation.invoke();
        }

        // 2. 再检查 Session
        Object user = session.get("user");
        if (user == null) {
            // 未登录,记录目标 URL,方便登录后跳转
            String queryString = ctx.getParameters().get("request").toString();
            session.put("redirectUrl", ctx.getName() + (queryString == null ? "" : "?" + queryString));
            return Action.LOGIN;   // 对应 <result name="login" type="redirect">/login</result>
        }

        // 3. 已登录,把 user 对象放到 ValueStack,页面可直接 <s:property value="user.name"/>
        ctx.getValueStack().set("user", user);
        return invocation.invoke();
    }
}
  1. 在 struts.xml 中注册
<package name="default" namespace="/" extends="struts-default">
    <!-- 1. 声明拦截器 -->
    <interceptors>
        <interceptor name="auth" class="cn.xxx.interceptor.AuthenticationInterceptor">
            <!-- 白名单:登录、注册、验证码 -->
            <param name="excludeActions">/login,/register,/captcha/*</param>
        </interceptor>

        <!-- 2. 定义新栈,把认证拦截器放在 defaultStack 之前 -->
        <interceptor-stack name="appStack">
            <interceptor-ref name="auth"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>

    <!-- 3. 指定默认栈,所有 Action 自动生效 -->
    <default-interceptor-ref name="appStack"/>

    <!-- 4. 全局结果 -->
    <global-results>
        <result name="login" type="redirect">/login</result>
    </global-results>
</package>
  1. 登录 Action 片段(供参考)
public String execute(){
    User u = userService.find(username, password);
    if(u!=null){
        ActionContext.getContext().getSession().put("user", u);
        // 登录后跳转
        String redirectUrl = (String) ActionContext.getContext().getSession().get("redirectUrl");
        if(redirectUrl!=null && !redirectUrl.isEmpty()){
            return "redirect:"+redirectUrl;
        }
        return SUCCESS;
    }
    addFieldError("msg","用户名或密码错误");
    return INPUT;
}

至此,AuthenticationInterceptor 已能 线程安全地验证 Session 中的 user 对象,并通过 白名单机制 避免拦截登录请求,符合国内 90% 企业 Struts2 项目的落地规范。

拓展思考

  1. 前后端分离场景:若公司已将前端改为 Vue/React,Struts2 仅提供 JSON 接口,则拦截器返回 自定义错误码 401 即可,前端根据状态码跳转登录页。
  2. 权限细粒度控制:在 user 对象里放 Set<String> permissions,再写 PermissionInterceptor 与 @RequiredPermission("order:add") 注解,基于注解 + OGNL 实现方法级鉴权,可无缝替代部分 Spring Security 功能。
  3. 分布式 Session:当应用多节点部署时,把 Session 存入 Redis,使用 Struts2 的 SessionMap 插件 或 Spring Session,拦截器代码无需改动,只需替换 Session 实现。
  4. 性能优化:对静态资源 /static/* 建议 直接在 nginx/apache 层返回,不走 Tomcat 与 Struts2 过滤器;同时 开启 struts.action.excludePattern=/static/.*.(js|css|png)$,降低拦截器无效执行次数。