• Struts2自定义拦截器


    自定义拦截器

    1). 具体步骤

    I. 定义一个拦截器的类

    > 可以实现 Interceptor 接口
    > 继承 AbstractInterceptor 抽象类

    II然后在拦截器类的interceptor()方法中定义这个拦截器的功能

    III. 在 struts.xml 文件配置.

    1注册拦截器

    <interceptors>
    <interceptor name="hello" class="com.atguigu.struts2.interceptors.MyInterceptor"></interceptor>
    </interceptors>
    2使用拦截器:<interceptor-ref name="hello"></interceptor-ref>
    <action name="testToken" class="com.atguigu.struts2.token.app.TokenAction">
    <interceptor-ref name="hello"></interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result>/success.jsp</result>
    <result name="invalid.token">/token-error.jsp</result>
    </action>
    III. 注意: 在自定义的拦截器中可以选择不调用 ActionInvocation 的 invoke() 方法. 那么后续的拦截器和 Action 方法将不会被调用.
    Struts 会渲染自定义拦截器 intercept 方法返回值对应的 result(比如验证用户权限、验证用户是否登录)

    意外的收获:

    1若想Struts2中的拦截器的属性可以参照下面

    <interceptors>
    <interceptor-stack name="atguigustack">
    <interceptor-ref name="defaultStack">
    <param name="fileUpload.maximumSize">2097152</param>
    <!--
    <param name="fileUpload.allowedTypes">text/html,text/xml</param>
    <param name="fileUpload.allowedExtensions">html,dtd,xml</param>
    -->
    </interceptor-ref>
    </interceptor-stack>
    </interceptors>
    然后再把默认拦截器栈变为自己定义的拦截器栈,这一步一定要,没有的话Struts2不能被加载
    <default-interceptor-ref name="atguigustack"></default-interceptor-ref>

    2若想自己定义的拦截器被全部Action都能使用,可以使用以下方方式:

    <package name="FileUploadTest" namespace="/" extends="struts-default"> 
            <!-- 注册自定义的拦截器 -->
            <interceptors>
                <interceptor name="hello" class="com.atguigu.struts2.Interceptor.app.TestInterceptor"></interceptor>
                
           
                <!-- 配置全部Action使用的拦截器 -->
                
                <interceptor-stack name="atguigustack">
                        <interceptor-ref name="hello"></interceptor-ref>
                        <interceptor-ref name="defaultStack"></interceptor-ref>
               </interceptor-stack>
            </interceptors>
            
                <!-- 使用自己修改后的拦截器栈 -->
                <default-interceptor-ref name="atguigustack"></default-interceptor-ref>
                
  • 相关阅读:
    腾讯云CentOS7学习
    听力词汇发音练习软件
    中缀表达式转后缀表达式
    两个升序序列的中位数
    CentOS配置静态IP
    一种简单的基于图像或激光雷达的道路(赛道)识别程序
    Win10+VS2019 配置YOLOv3
    【算法题】CCF CSP第二题练习(更新中)
    rpm的使用
    SCL
  • 原文地址:https://www.cnblogs.com/jeremy-blog/p/3995563.html
Copyright © 2020-2023  润新知