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

Struts2的拦截器
一、Struts2的拦截器只能拦截Action,拦截器是AOP的一种思路,能够使咱们的系统架构
更松散(耦合度低),能够插拔,容易互换,代码不改变的状况下很容易知足客户需求
其实体现了OCP
 
二、如何实现拦截器?(整个拦截器体现了责任链模式,Filter也体现了责任链模式)
* 继承AbstractInterceptor(体现了缺省适配器模式,建议使用该模式)
* 实现Interceptor
 
三、若是自定了拦截器,缺省拦截器会失效,必须显示引用Struts2默认的拦截器
 
四、拦截器栈,多个拦截器的和
 
五、定义缺省拦截器<default-interceptor-ref>,全部的Action都会使用
 
六、拦截器的执行原理,在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>
相关文章
相关标签/搜索