Struts2--自定义拦截器三种方式(实现Interceptor接口、继承抽象类AbstractInterceptor、继承MethodFilterInterceptor)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/cold___play/article/details/102651720

实现自定义拦截器

在实际的项目开发中,虽然 Struts2 的内建拦截器可以完成大部分的拦截任务,但是,一些与系统逻辑相关的通用功能(如权限的控制和用户登录控制等),则需要通过自定义拦截器实现。本节将详细讲解如何自定义拦截器。

1.实现Interceptor接口

在 Struts2 框架中,通常开发人员所编写的自定义拦截器类都会直接或间接地实现 com.opensymphony.xwork2.interceptor.Interceptor 接口。Interceptor 接口中的主要代码如下所示:

public interface Interceptor extends Serializable{
    void init();
    void destroy();
    String intercept(ActionInvocation invocation) throws Exception;
}

从上述代码中可以看出,该接口共提供了以下三个方法。

1)void init()
该方法在拦截器被创建后会立即被调用,它在拦截器的生命周期内只被调用一次。可以在该方法中对相关资源进行必要的初始化。

2)void destroy()
该方法与 init() 方法相对应,在拦截器实例被销毁之前,将调用该方法释放和拦截器相关的资源,它在拦截器的生命周期内,也只被调用一次。

3)String intercept(ActionInvocation invocation)throws Exception

该方法是拦截器的核心方法,用于添加真正执行拦截工作的代码,实现具体的拦截操作,它返回一个字符串作为逻辑视图,系统根据返回的字符串跳转到对应的视图资源。每拦截一个动作请求,该方法就会被调用一次。

该方法的 ActionInvocation 参数包含了被拦截的 Action 的引用,可以通过该参数的 invoke() 方法,将控制权转给下一个拦截器或者转给 Action 的 execute() 方法。

2.继承抽象类AbstractInterceptor

AbstractIntercepter 类实现了 Interceptor 接口,并且提供了 init() 方法和 destroy() 方法的空实现。使用时,可以直接继承该抽象类,而不用实现那些不必要的方法。AbstractInterceptor 类中定义的方法如下所示:

public abstract class AbstractInterceptor implements Interceptor{
    public void init(){}
    public void destroy(){}
    public abstract String intercept (ActionInvocation invocation) throws Exception;
}

AbstractInterceptor 类已经实现了 Interceptor 接口的所有方法,一般情况下,只需继承 AbstractInterceptor 类,实现 interceptor() 方法就可以创建自定义拦截器。

需要注意的是,只有当自定义的拦截器需要打开系统资源时,才需要覆盖 AbstractInterceptor 类的 init() 方法和 destroy() 方法。与实现 Interceptor 接口相比,继承 AbstractInterceptor 类的方法更为简单。

扫描二维码关注公众号,回复: 7615600 查看本文章

3.继承MethodFilterInterceptor

MethodFilterInterceptor提供了一个doIntercept方法供我们实现拦截器功能。


public abstract class MethodFilterInterceptor extends AbstractInterceptor {
    /**
     * Subclasses must override to implement the interceptor logic.
     * 
     * @param invocation the action invocation
     * @return the result of invocation
     * @throws Exception
     */
    protected abstract String doIntercept(ActionInvocation invocation) throws Exception;
    
}

示例:

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

//继承:MethodFilterInterceptor 方法过滤拦截器
//功能: 定制拦截器拦截的方法.
//	定制哪些方法需要拦截.
//	定制哪些方法不需要拦截
public class MyInterceptor3 extends MethodFilterInterceptor{

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		//前处理
		System.out.println("MyInterceptor3 的前处理!");
		//放行
		String result = invocation.invoke();
		//后处理
		System.out.println("MyInterceptor3 的后处理!");
		
		return result;
	}

}

猜你喜欢

转载自blog.csdn.net/cold___play/article/details/102651720
今日推荐