struts2学习笔记之十三:自定义过滤器

Struts2的拦截器
1、Struts2的拦截器只能拦截Action,拦截器是AOP的一种思路,可以使我们的系统架构
更松散(耦合度低),可以插拔,容易互换,代码不改变的情况下很容易满足客户需求
其实体现了OCP
 
2、如何实现拦截器?(整个拦截器体现了责任链模式,Filter也体现了责任链模式)
* 继承AbstractInterceptor(体现了缺省适配器模式,建议使用该模式)
* 实现Interceptor
 
3、如果自定了拦截器,缺省拦截器会失效,必须显示引用Struts2默认的拦截器
 
4、拦截器栈,多个拦截器的和
 
5、定义缺省拦截器<default-interceptor-ref>,所有的Action都会使用
 
6、拦截器的执行原理,在ActionInvocation中有一个成员变量Iterator,这个Iterator中保存了所有的
拦截器,每次都会取得Iterator进行next,如果找到了拦截器就会执行,否则就执行Action,都执行完了
拦截器出栈(其实出栈就是拦截器的intercept方法弹出栈)
 
自定义拦截器myLogInterceptor.java
package com.djoker.struts2;

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

public class myLogInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("记录日志开始");
        
        String recode = invocation.invoke();
        
        System.out.println("记录日志结束");
        
        
        return recode;
    }

}
struts.xml配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
    <package name="user" extends="struts-default" namespace="/user">
        <interceptors>
            <!-- 声明过滤器 -->
            <interceptor name="mylog" class="com.djoker.struts2.myLogInterceptor"></interceptor>
            <!-- 使用站方式声明过滤器 -->
            <interceptor-stack name="myStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="mylog"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 默认拦截器,如果没有指定则使用该拦截器 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        <global-exception-mappings>
            <exception-mapping result="error" exception="com.djoker.struts2.UserNotFoundException"></exception-mapping>
        </global-exception-mappings>
        <action name="*User" class="com.djoker.struts2.UserAction" method="{1}User">
            <!-- 普通配置,但是每个Action都需要配置
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <interceptor-ref name="mylog"></interceptor-ref>
             -->
             <!--  
             <interceptor-ref name="mylog"></interceptor-ref>
             -->
            <exception-mapping result="error" exception="com.djoker.struts2.UserNotFoundException"></exception-mapping>
            <result>/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>
原文地址:https://www.cnblogs.com/djoker/p/6219691.html