Struts2之拦截器和过滤器及其区别

拦截器和过滤器及其区别(转载自http://blog.51cto.com/myoraclex/414351):
1、拦截器是基于java反射机制的,而过滤器是基于函数回调的。
2、过滤器依赖于servlet容器,而拦截器不依赖于servlet容器。
3、拦截器只能对Action请求起作用,而过滤器则可以对几乎所有请求起作用。
4、拦截器可以访问Action上下文、值栈里的对象,而过滤器不能。
5、在Action的生命周期中,拦截器可以多次调用,而过滤器只能在容器初始化时被调用一次。

1.拦截器

1.1 拦截器介绍

官方文档解释:
An interceptor is a stateless class that follows the interceptor pattern, as found in Filter and in AOP languages.
Interceptors are objects that dynamically intercept Action invocations. They provide the developer with the opportunity to define code that can be executed before and/or after the execution of an action. They also have the ability to prevent an action from executing. Interceptors provide developers a way to encapsulate common functionality in a re-usable form that can be applied to one or more Actions.
Google翻译:
拦截器是一个遵循拦截器模式的无状态类,如Filter和AOP语言中所示。
拦截器是动态拦截Action调用的对象。 它们为开发人员提供了定义可在执行操作之前或之后执行的代码的机会。 它们还具有阻止执行操作的能力。 拦截器为开发人员提供了一种方法,可以将通用功能封装在可重用的表单中,该表单可以应用于一个或多个操作。

附上struts2的官方核心原理图(来自黑马课程):
这里写图片描述
拦截器就是在Action动作方法前后执行,如果存在多个拦截器就按顺序执行,在返回Response之前反过来执行一遍。
拦截器常用来做权限的验证、日志记录等。

1.2 自定义拦截器

1.2.1 自定义拦截器类
public class MyInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("在action方法之前执行...");
        String result = invocation.invoke();
        System.out.println("在action方法之后执行...");
        return result;
    }

}
1.2.2 Action定义
public class MyAction {
    public String execute() {
        System.out.println("action方法执行...");
        return "success";
    }
}
1.2.3 struts.xml文件配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="xxx" extends="struts-default">
        <interceptors>
        <!-- 定义自定义拦截器声明 -->
            <interceptor name="myInterceptor" class="com.itheima.interceptor.MyInterceptor">
            </interceptor>
        </interceptors>
        <action name="myAction" class="com.itheima.action.MyAction">
            <result name="success">/welcome.jsp</result>
            <!--使用拦截器  -->
            <interceptor-ref name="myInterceptor"></interceptor-ref>
            <!--显式配置默认拦截器,因为使用自定义拦截器时默认拦截器会失效 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>
    </package>

</struts>

welcome.jsp略….
浏览器访问:http://localhost:8080/Demo02-Interceptor/myAction
后台console:
后台console

2 过滤器

待续…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值