当前位置: 首页 > 编程笔记 >

SpringBoot添加自定义拦截器的实现代码

田阳泽
2023-03-14
本文向大家介绍SpringBoot添加自定义拦截器的实现代码,包括了SpringBoot添加自定义拦截器的实现代码的使用技巧和注意事项,需要的朋友参考一下

在Controller层时,往往会需要校验或验证某些操作,而在每个Controller写重复代码,工作量比较大,这里在Springboot项目中 ,通过继承WebMvcConfigurerAdapter,添加拦截器。

1、WebMvcConfigurerAdapter源码

/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.web.servlet.config.annotation;
import java.util.List;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
/**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested in.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addFormatters(FormatterRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureViewResolvers(ViewResolverRegistry registry) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation is empty.
   */
  @Override
  public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
  }
  /**
   * {@inheritDoc}
   * <p>This implementation returns {@code null}.
   */
  @Override
  public Validator getValidator() {
    return null;
  }
  /**
   * {@inheritDoc}
   * <p>This implementation returns {@code null}.
   */
  @Override
  public MessageCodesResolver getMessageCodesResolver() {
    return null;
  }
}

可以看出,该类 还能配置其他很多操作,例如异常处理,跨域请求等配置。

2、自动义Web配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
  }
  @Bean
  public MyInterceptor getMyInterceptor(){
    return new MyInterceptor();
  }
}

  如果需要添加多个拦截器,InterceptorRegistry registry.addInterceptor方法

public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) {
    InterceptorRegistration registration = new InterceptorRegistration(interceptor);
    this.registrations.add(registration);
    return registration;
  }

registrations是个数组结构,可以添加多个

3、自动义拦截器

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class MyInterceptor extends HandlerInterceptorAdapter {
  final Logger logger = LoggerFactory.getLogger(getClass());
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //拦截操作
    return true;
  }
}

总结

以上所述是小编给大家介绍的SpringBoot添加自定义拦截器的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对小牛知识库网站的支持!

 类似资料:
  • 在RestTemplate中,我有一个自定义拦截器,它将记录一些请求-响应详细信息并保存到数据库。 我的自定义拦截器: springboot中的RestTemboard bean配置: 将拦截器添加到restTemboard bean: 如何将此拦截器添加到佯装客户端? 正在应用中。yml: InterceptorOne为假装客户端中的每个请求添加标头: 但是我不能添加日志服务拦截器,因为它由于错

  • 本文向大家介绍利用spring的拦截器自定义缓存的实现实例代码,包括了利用spring的拦截器自定义缓存的实现实例代码的使用技巧和注意事项,需要的朋友参考一下 本文研究的主要是利用spring的拦截器自定义缓存的实现,具体实现代码如下所示。 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态

  • 本文向大家介绍SpringBoot拦截器实现登录拦截的方法示例,包括了SpringBoot拦截器实现登录拦截的方法示例的使用技巧和注意事项,需要的朋友参考一下 源码 GitHub:https://github.com/291685399/springboot-learning/tree/master/springboot-interceptor01 SpringBoot拦截器可以做什么 可以对UR

  • 本文向大家介绍Spring MVC 拦截器实现代码,包括了Spring MVC 拦截器实现代码的使用技巧和注意事项,需要的朋友参考一下 拦截器的实现 1、编写拦截器类实现HandlerInterceptor接口; 2、将拦截器注册进springmvc框架中; 3、配置拦截器的拦截规则; 其他实现方法 WebRequestInterceptor接口: 与上一个的区别是参数区别和prehandle的方

  • null 我尝试将@priority(interceptor.priority.platform_beform)和@prematching也放入我的过滤器中,但即使是在OIDC启动后也会调用。 另外,是否有任何方法支持扩展quarkus oidc逻辑以包括自定义代码? 我无法获得oidc和keycloak-auth拦截器的优先级(知道这些可以帮助我决定过滤器的优先级)。请帮忙。

  • 以下是我的Spring应用程序的相关部分: 上面的方法从未被调用。我需要成为一个Spring bean,因为我需要向它注入其他依赖项。 以下是文件的相关部分: