深入理解 Struts 2 中的拦截器机制
在开发 web 应用程序时,我们经常需要对请求进行处理和过滤,Struts 2 提供了一种强大的框架来帮助开发者简化这一过程,拦截器(Interceptor)机制就是其中之一,它允许我们在特定的请求阶段执行自定义逻辑。
Struts 2 的拦截器系统提供了一种灵活的方式来添加自定义行为到请求链中,通过实现 org.apache.struts2.interceptor.Interceptor 接口,我们可以创建自己的拦截器,并在其方法中编写业务逻辑、数据验证或其他功能。
技术基础
在 Struts 2 中,拦截器的工作原理基于 ActionServlet 执行请求的过程,当客户端发送 HTTP 请求时,ActionServlet 负责将请求转发给相应的 Action 类(或其子类),并在中间件层处理请求之前调用所有已注册的拦截器。
创建和使用拦截器
要为某个请求注册一个拦截器,可以在配置文件(通常是 struts.xml 或 struts-config.xml)中添加如下配置:
<interceptors>
<interceptor name="customInterceptor" class="com.example.MyCustomInterceptor"/>
</interceptors>
<action name="myAction" class="com.example.MyAction">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="customInterceptor"/>
</action>
这里,MyCustomInterceptor 是你的拦截器类名,而 com.example.MyAction 是 Action 类的全限定名。
实现示例
假设你有一个简单的拦截器,用于验证用户是否登录过期,你可以这样实现:
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class LoginExpiredInterceptor extends MethodFilterInterceptor {
@Override
public boolean invoke(ActionInvocation invocation) throws Exception {
// 获取当前用户的会话信息
HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
String lastLoginDate = (String) session.getAttribute("lastLoginDate");
// 如果上次登录时间少于30天,则认为用户未登录
long now = System.currentTimeMillis();
long lastLoginTime = Long.parseLong(lastLoginDate);
long daysSinceLastLogin = (now - lastLoginTime) / (1000 * 3600 * 24);
if (daysSinceLastLogin > 30) {
return false; // 阻止访问并显示错误消息
}
return super.invoke(invocation);
}
}
在 struts.xml 文件中注册这个拦截器:
<interceptors>
<interceptor name="loginExpired" class="com.example.LoginExpiredInterceptor"/>
</interceptors>
<action name="myAction" class="com.example.MyAction">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="loginExpired"/>
</action>
Struts 2 的拦截器机制提供了强大的灵活性和可定制性,使开发者能够根据具体需求构建复杂的请求处理流程,通过深入理解和正确地应用拦截器,可以显著提高代码的组织性和效率,对于那些希望更精细控制 Web 程序请求处理的人来说,Struts 2 的拦截器机制是一个非常有价值的工具。

上一篇