拦截器和过滤器及其区别(转载自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:
2 过滤器
待续…