【Struts2三】拦截器

拦截器:就是在访问action之前,对其进行拦截!可以在拦截器中做一些逻辑的处理!比如权限验证,没有权限就不给予访问!
拦截器等效于servlet中的过滤器!

使用拦截器步骤:
1.定义自己的拦截器:
import  com.opensymphony.xwork2.ActionInvocation;
import  com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 定义自己的拦截器,需要实现Intercept接口!
 *
 */
public  class MyInterceptor implements Interceptor{

      public  void destroy() {
          
     }

      public  void init() {
          
     }
      /**
      * 重写intercept方法,在该方法中实现自己的拦截逻辑!
      * 调用invocation.invoke()方法放行action!
      */
      public  String intercept(ActionInvocation invocation) throws Exception {
          System.  out.println("图片上传" );
            return invocation.invoke();
//        return null;//不执行action
     }

}


2.在struts-interceptor.xml的配置文件中声明:
  需要在struts.xml中包含上述配置文件!

struts-interceptor.xml:
<? xml  version= "1.0" encoding ="UTF-8" ?>
<! DOCTYPE  struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
     "http://struts.apache.org/dtds/struts-2.0.dtd">
< struts >
      < package  name="interceptor" namespace="/" extends="struts-default" >
            <!-- 声明拦截器,拦截器声明应该位于action之前-->
            <interceptors>
                <!--声明自己定义的拦截器 -->
                <interceptor name= "imageInterceptor"
                     class= "cn.itheima03.struts2.interceptor.MyInterceptor" ></interceptor>

                <!-- 声明拦截器栈 -->
                <interceptor-stack name= "myInterceptor">
                     <interceptor-ref name="imageInterceptor" ></interceptor-ref>
                     <interceptor-ref name="defaultStack" ></interceptor-ref>
                </interceptor-stack>
            </interceptors>

            <!-- 修改默认的拦截器栈 -->
            <default-interceptor-ref name="myInterceptor" ></default-interceptor-ref>

            <!--声明action,在执行action之前,会先执行拦截器中的方法  -->
            <action name= "interceptorAction_*" method ="{1}"
                 class= "cn.itheima03.struts2.interceptor.InterceptorTestAction" >
                <result>
                   index.jsp
                </result>
            </action>
      </ package  >

</ struts >

3.定义action:
import  com.opensymphony.xwork2.ActionSupport;

public  class InterceptorTestAction extends ActionSupport{
      public  String interceptor(){
          System.  out.println("interceptor" );
            return SUCCESS ;
     }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值