码迷,mamicode.com
首页 > 其他好文 > 详细

Struts2自定义拦截器

时间:2014-09-27 00:47:58      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   文件   sp   div   

自定义拦截器

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>
            

 

Struts2自定义拦截器

标签:style   blog   color   io   使用   ar   文件   sp   div   

原文地址:http://www.cnblogs.com/jeremy-blog/p/3995563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!