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元素中选择实现的拦截器类,就可以使用自定义拦截器了。

  • 相关阅读:
    [转] Actor生命周期理解
    [转] Linux History(历史)命令用法 15 例
    [转] CDH6 安装文章链接收集
    [转] org.scalatest.FunSuite Scala Examples
    [转] Mock以及Mockito的使用
    关于 maven 打包直接运行的 fat jar (uber jar) 时需要包含本地文件系统第三方 jar 文件的问题
    [转] flume使用(六):后台启动及日志查看
    [转] etcd 搭建与使用
    [转] 2018年最新桌面CPU性能排行天梯图(含至强处理器)
    让 Linux grep 的输出不换行
  • 原文地址:https://www.cnblogs.com/GG-Bond/p/10544672.html
Copyright © 2011-2022 走看看