zoukankan      html  css  js  c++  java
  • Struts2之拦截器

    拦截器:在Action执行之前和之后进行一些额外的操作,相当于过滤器

    拦截器的工作方式 

    1、拦截器

    <interceptor name="privilege" class="com.test.interceptor.PrivilegeInterceptor"></interceptor>

      name-拦截器名称

      class-拦截器的实现类

    2、拦截器栈

    在实际开发中,需要在Action执行前执行多个拦截器,这时可以把多个拦截器组成一个拦截器栈,可以将栈内的多个拦截器当作一个整体来引用。

    定义拦截器栈使用<interceptor-stack>

      name-拦截器栈名

    定义多个拦截器使用<interceptor-ref>

    <interceptor-stack name="myStack">
           <interceptor-ref name="defaultStack"></interceptor-ref>
           <interceptor-ref name="privilege"></interceptor-ref>
    </interceptor-stack>

    在Action中声明拦截器使用<interceptor-ref>

    <action name="book_*" class="com.test.Action.BookAction" method="{1}">
                <result>/success2.jsp</result>
                <result name="login">/login.jsp</result>
                <interceptor-ref name="myStack"></interceptor-ref>
    </action>

    3、默认拦截器

    如果相对一个包(package)中的Action使用相同的拦截器,使用默认拦截器更方便些

    <default-interceptor-ref>

    <default-interceptor-ref name="defaultStack"></interceptor-ref>

    默认拦截器在包内声明,若包内Action未显示的指定拦截器,则使用默认浏览器,若Action指定了拦截器,则覆盖掉默认拦截器。

    一个包下只有一个默认拦截器,若想要多个默认拦截器,先将需要设置为默认的拦截器设置为拦截器栈,再使用default指定拦截器栈。

    4、自定义拦截器

     建立一个java类继承AbstractInterceptor重写

    public String intercept(ActionInvocation invocation) throws Exception{return null;}
    public class PrivilegeInterceptor extends AbstractInterceptor {
        @Override
        public String intercept(ActionInvocation invocation) throws Exception{
            ActionContext ac=invocation.getInvocationContext();
            Object user = ac.getSession().get("user");
            if (user!=null){
                return invocation.invoke();
            }else {
                ac.put("msg","未登录,请先登录");
                return Action.LOGIN;
            }
        }
    }
    <interceptor name="privilege" class="com.test.interceptor.PrivilegeInterceptor"></interceptor>

    在<interceptor>的class元素中选择实现的拦截器类,就可以使用自定义拦截器了。

  • 相关阅读:
    《入门经典》——6.15
    《Linear Algebra and Its Application》-chaper1-行化简法解决线性方程组
    《算法实战策略》-chaper19-队列、栈和双端队列
    《Linear Algebra and Its Applications》-chaper1-向量方程、矩阵方程和线性方程组
    辛普森法则
    《训练指南》——6.15
    《入门经典》——6.21
    《算法问题实战策略》-chaper13-数值分析
    Scheme 中的 pair 和 list 简述
    C. Friends
  • 原文地址:https://www.cnblogs.com/GG-Bond/p/10544672.html
Copyright © 2011-2022 走看看