1. 首页
  2. 软件开发
  3. Spring MVC——拦截器(Interceptor)的配置和使用多种方式

Spring MVC——拦截器(Interceptor)的配置和使用多种方式

  • 发布于 2024-08-17
  • 0 次阅读

拦截器(Interceptor)在Spring MVC中用于在请求处理的不同阶段进行拦截和处理,类似于过滤器,但更加灵活。

拦截器配置和使用方式:

  1. 实现HandlerInterceptor接口:

    • 创建一个拦截器类,实现HandlerInterceptor接口,重写preHandle、postHandle和afterCompletion方法。

    • 在Spring配置文件中配置拦截器:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/secure/**"/>
        <bean class="com.example.CustomInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>
  1. 继承HandlerInterceptorAdapter类:

    • 创建一个拦截器类,继承HandlerInterceptorAdapter类,重写preHandle、postHandle和afterCompletion方法。

    • 在Spring配置文件中配置拦截器:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/secure/**"/>
        <bean class="com.example.CustomInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>
  1. 使用注解方式:

    • 创建一个拦截器类,使用@Component注解标记,实现HandlerInterceptor接口。

    • 在配置类上添加@EnableWebMvc注解,注册拦截器:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
   
    
    @Autowired
    private CustomInterceptor customInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
   
        registry.addInterceptor(customInterceptor).addPathPatterns("/secure/**");
    }
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/138026410