Spring mvc Interceptor 拦截器学习

SpringMVC中的interceptor可以说是过滤器的一部分,可以用来进行权限认证或登录检测等

(一)定义interceptor类

1.通过实现handleInterceptor接口或者继承实现了handleinterceptor接口的类
2.通过实现webrequestInterceptor接口或者继承实现了webrequestInterceptor接口的类

一.实现handleInterceptor接口
handleInterceptor接口有三个方法
1.preHandle():在请求处理之前调用,顺序调用,链式调用,可以在这个函数中进行一些预处理,并且当他的返回值的false的时候,之后的拦截器函数和contoller都不会执行。
2.postHandle():在contoller执行之后,在dispatcherSercket视图返回渲染之前调用,所以我们可以在这个
3.afterCompletion():在所有执行完之后执行,即在视图返回渲染之后调用,用于资源回收等。
二.实现webrequestInterceptor接口
和一类似,不做赘述。

(二)将拦截器加载到SpringMVC的拦截体系里去

1、在SpringMVC的配置文件中加上支持MVC的schema
xml代码:

  xmlns:mvc="http://www.springframework.org/schema/mvc"  
  xsi:schemaLocation=" http://www.springframework.org/schema/mvc  
  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"  

进行声明:

    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
         http://www.springframework.org/schema/context  
         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
         http://www.springframework.org/schema/mvc  
         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  

之后就可以使用mvc标签了,mvc标签中有一项<mvc:interceptor>是用于声明SpringMVC拦截器的

2.使用mvc:interceptors标签来声明需要加入到SpringMVC拦截器链中的拦截器
事例:

    <mvc:interceptors>  
        <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->  
        <bean class="com.host.app.web.interceptor.AllInterceptor"/>  
        <mvc:interceptor>  
            <mvc:mapping path="/test/number.do"/>  
            <!-- 定义在mvc:interceptor下面的表示是对单个的请求才进行拦截的 -->  
            <bean class="com.host.app.web.interceptor.LoginInterceptor"/>  
        </mvc:interceptor>  
    </mvc:interceptors>  

在<mvc:interceptors>中声明类有两种方式:
①直接定义一个interceptor类的bean对象,他会对所有的请求进行拦截
②用mvc:interceptor定义,在其中使用,mvc:mapping指定要拦截的对象,用mvc:exclude-mapping排除不用拦截的对象

本篇博客参考大佬:
https://elim.iteye.com/blog/1750680
https://blog.csdn.net/chenleixing/article/details/44573495

发布了28 篇原创文章 · 获赞 1 · 访问量 657

猜你喜欢

转载自blog.csdn.net/c630843901/article/details/95061148