struts2-自定义struts拦截器interceptor

本文介绍了如何在Struts2中开发自定义拦截器。首先,你需要创建一个拦截器类,实现Interceptor接口或继承AbstractInterceptor抽象类。接着,在struts.xml配置文件中声明并使用拦截器,确保引用了默认的defaultStack。拦截器的核心在于ActionInvocation的回调机制,通过invocation.invoke()实现拦截链的执行。示例中展示了两种不同的拦截器实现方式。

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

实际开发自然避免不了增加符合需求的拦截器,那么如何来开发呢?根据源码的结构分析,大概有两个步骤。

定义一个拦截器类

和自定义filter过滤器一样,自定义的拦截器类也要实现Interceptor接口,或者继承AbstractInterceptor抽象类。
要注意导入包的路径,是基于xwork2框架的包。

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
 * @className TestInterceptor
 * @date 2021/4/24 13:13
 * @description
 **/
public class TestInterceptor implements Interceptor {
    @Override
    public void destroy() {}
    @Override
    public void init() {}
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        return null;
   }
}
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
 * @className InterceptorTest
 * @date 2021/4/24 13:14
 * @description
 **/
public class InterceptorTest extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        return null;
    }
}

在struts.xml在配置和使用

注意在引用自定义interceptor时还要加上默认的defaultStack 拦截器栈。
当然,拦截器的intercept()方法要根据需要实现。

<package name="default" namespace="/" extends="struts-default">
   <interceptors>
       <interceptor name="interceptorTest" class="com.example.interceptor.InterceptorTest"></interceptor>
       <interceptor name="testInterceptor" class="com.example.interceptor.TestInterceptor"></interceptor>
   </interceptors>

   <action name="test" class="com.example.action.TestAction">
       <interceptor-ref name="interceptorTest"></interceptor-ref>
       <interceptor-ref name="defaultStack"></interceptor-ref>
       <result>/success.jsp</result>
   </action>
</package>

注意

@Override
public String intercept(ActionInvocation invocation) throws Exception {
	System.out.println("before invocation.invoke...");
	//调用invoke()方法实现后续interceptor的回调
	String result = invocation.invoke();
	System.out.println("after invocation.invoke...");
return "success";
}

根据原理可知,完整拦截器栈所有的intercept()方法靠的就是ActionInvocation的回调,所以要加上String result = invocation.invoke();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值