传智播客学习日记Day24

来源:互联网 发布:哪有好的java培训 编辑:程序博客网 时间:2024/06/04 21:55
今天是学习Struts的第二天,这天要学习的主要有:拦截器(如何配置拦截器,拦截器的原理,编写自己的拦截器)。
老师首先对拦截器进行了基础讲解,然后教我们编写一个拦截器,可以拦截未登入的用户,直接访问特定的action.

拦截器
Struts2为一个Action自动注入的各种功能都是通过各种拦截器实施上去的。

自己定义一个拦截器,需要继承AbstractInterceptor,或实现Interceptor
    public class LogIntegerceptor extends AbstractInterceptor {
    
    @Override
    public void init() {
        System.out.println("LogIntegerceptor init");
    }

    @Override
    public void destroy() {
        System.out.println("LogIntegerceptor destroy");
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println(" LogIntegerceptor  intercept");
        return invocation.invoke();
    }
}

配置拦截器
    在package中定义一个拦截器
        <interceptors>
            <interceptor name="logInterceptor" class="cd.itcast.struts2day24.log.LogIntegerceptor"></interceptor>
        </interceptors>
        
 使用拦截器,使用interceptor-ref把指定名称的拦截器配置到action上.如果在某个action使用interceptor-ref配置了拦截器以后,默认的拦截器将不起作用.
        1.
        <interceptor-ref name="defaultStack"></interceptor-ref>
        <interceptor-ref name="logInterceptor"></interceptor-ref>
        

        2.
          配置一个拦截器栈
            <interceptor-stack name="myStack">
                <interceptor-ref name="logInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        使用一个拦截器栈进行拦截
            <interceptor-ref name="myStack"></interceptor-ref>
        
        3.
        <!--  默认的拦截器,如果actio中没有另外指定拦截器,则这里的拦截器是通用的 -->
        <default-interceptor-ref name="myStack"/>