struts2的自定义拦截器和配置

来源:互联网 发布:单片机开发论坛 编辑:程序博客网 时间:2024/05/16 08:44
1.编写拦截器,需要实现Interceptor接口,实现接口中的三个方法。    * interceptor接口有很多的实现类,编写最简单的方式就是继承AbstractInterceptor实现类。          * 代码例如:        public String intercept(ActionInvocation invocation) throws Exception {            User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");            if(user == null){                ActionSupport as = (ActionSupport) invocation.getAction();                as.addActionError("您没有登陆!");                return as.LOGIN;            }else{                // 放行                return invocation.invoke();            }        }    * 需要在struts.xml中进行拦截器的配置,配置一共有两种方式:        > 第一种方式            * 在<package>包中定义拦截器,出现在<package>包的上方                <interceptors>                    <interceptor name="loginInterceptor" class="cn.itcast.interceptor.LoginInterceptor"></interceptor>                </interceptors>                     * 在某个action中引入拦截器                <interceptor-ref name="loginInterceptor"></interceptor-ref>                * 注意:如果引入了自己定义的拦截器,那么Struts2框架默认的拦截器就不会再执行了,所以需要引入Struts2默认的拦截器。                    <interceptor-ref name="defaultStack"></interceptor-ref>                     > 第二种方式            * 在<package>包中定义拦截器的时候,自己直接定义一个拦截器栈                <interceptors>                    <interceptor name="loginInterceptor" class="cn.itcast.interceptor.LoginInterceptor"/>                    <interceptor-stack name="myStack">                        <interceptor-ref name="loginInterceptor"/>                        <interceptor-ref name="defaultStack"/>                    </interceptor-stack>                </interceptors>            * 在Action包中引入自己定义的拦截器栈                <action name="book_*" class="cn.itcast.action.BookAction" method="{1}">                    <interceptor-ref name="myStack"/>                </action>
0 0
原创粉丝点击