java – Spring boot:如何在静态资源中添加拦截器?

栏目: Java · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/46446115/spring-boot-how-to-add-interceptors-to-static-resources

我在/ static / img / **中有几个文件夹,我需要在其中一些文件夹中添加拦截器来检查用户权限.我之前使用过拦截器并以这种方式添加它们:

@SpringBootApplication
@EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {

  ...

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
      .addResourceHandler("/static/**")
      .addResourceLocations("classpath:/static/");
  }

  @Bean
  public AuthHeaderInterceptor authHeaderInterceptor() {
    return new AuthHeaderInterceptor();
  }

  @Bean
  public AuthCookieInterceptor authCookieInterceptor() {
    return new AuthCookieInterceptor();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry
      .addInterceptor(authHeaderInterceptor())
      .addPathPatterns(REST_URL)
      .excludePathPatterns(
        new String[] {
          REST_SECURITY_URL,
          REST_SETTINGS_URL,
          REST_REPORTS_URL
        }
      );

    registry
      .addInterceptor(authCookieInterceptor())
      .addPathPatterns(REST_REPORTS_URL);
  }
}

一切都适用于休息控制器及其URL,但现在我需要保护一些静态资源,我添加了这个:

@SpringBootApplication
@EnableTransactionManagement
public class Application extends WebMvcConfigurerAdapter {

  ...

  @Bean 
  public RoleAdminInterceptor roleAdminInterceptor() {
    return new RoleAdminInterceptor();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry
      .addInterceptor(authHeaderInterceptor())
      .addPathPatterns(REST_URL)
      .excludePathPatterns(
        new String[] {
          REST_SECURITY_URL,
          REST_SETTINGS_URL,
          REST_REPORTS_URL
        }
      );

    //THIS NOT WORK
    registry
      .addInterceptor(roleAdminInterceptor())
      .addPathPatterns("/static/img/admin/**");

    registry
      .addInterceptor(authCookieInterceptor())
      .addPathPatterns(REST_REPORTS_URL);
  }
}

注释行不起作用.当我向/static/img/admin/test.png发送请求时,从不调用RoleAdminInterceptor.

我做错了什么?

我认为在这种情况下你可以使用带有Spring安全性的过滤器而不是拦截器,因为你可以在点击拦截器之前验证进程早期的访问,除非你有一个特定的用例需要在这里使用拦截器.

关于这两者之间的区别的一些主题:

filters-vs-interceptor

翻译自:https://stackoverflow.com/questions/46446115/spring-boot-how-to-add-interceptors-to-static-resources


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

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

编程语言

编程语言

图科 / 李德龙 / 清华大学 / 2008-1 / 68.00元

本书第1版自1999年出版以来,编程语言的研究已得到迅猛发展。为此,新版尽量贴近现今的发展趋势,以适应当前和未来编程语言设计过程中所伴随的新挑战。本书除了进一步提高了4种程序设计范型及其所用的语言的广度和深度外,还大大丰富了关于语言设计原理的内容,并新增了如Python、Perl这类编程语言的例子。本书主要结构第一部分:原理。第2、4、5、7、9章分别讲述了编程语言的5个核心原理(语法、名称、类型......一起来看看 《编程语言》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具