栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot如何添加拦截器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot如何添加拦截器

构建一个spring boot项目。

添加拦截器需要添加一个configuration

@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

为了方便扫描位置,我们可以写一个接口或者入口类Application放置于最外一层的包内,这样就会扫描该类以及子包的类。

 1 resources配置

在没有配置这个类的时候,我们可以在application.ym中修改静态文件位置和匹配方式:

#指定环境配置文件
spring:
 profiles:
  active: dev
 # 修改默认静态路径,默认为
public class LoginInterceptor extends HandlerInterceptorAdapter {
  private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String authorization = request.getHeader("Authorization");
    logger.info("The authorization is: {}",authorization);
    return super.preHandle(request, response, handler);
  }
}

写好interceptor之后需要在开始创建的ServletContextConfig中添加这个拦截器:

@Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginInterceptor())
 .addPathPatterns("
@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

  static final private String FAVICON_URL = "/favicon.ico";
  static final private String PROPERTY_APP_ENV = "application.environment";
  static final private String PROPERTY_DEFAULT_ENV = "dev";



  
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/").addResourceLocations("
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginInterceptor())
 .addPathPatterns("/**")
 .excludePathPatterns(FAVICON_URL)
    ;
  }

}

github地址https://github.com/chenxing12/spring-boot-demo

本demo源码:spring-boot-demo_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/146881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号