【问题标题】:Couldn't access jpg file under resources/static folder无法访问资源/静态文件夹下的 jpg 文件
【发布时间】:2021-03-10 15:02:59
【问题描述】:

我无法访问resources/static 文件夹下的图像。我正在使用 Spring Boot 2.112 版。

我也尝试在属性文件中添加 spring.resources.static-locations,但仍然无法从 resources/static/image 文件夹访问 .jpg 文件。有什么原因吗?

@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/static/", "classpath:/image/");
    }

【问题讨论】:

  • 您的资源似乎在classpath:/static/image 文件夹中......您可以将其添加到您的配置中并进行测试吗?
  • 我这样做了,但没有用..

标签: spring spring-boot spring-mvc


【解决方案1】:

好吧,你可以试试https://stackoverflow.com/a/66361120/15215155。大部分时间都是关于spring boot默认的安全配置。

编辑:这里很少编辑,因为对于 cmets 来说太多了。

从另一个角度解决问题。 WebMvcConfigurationSupport 是否有您需要的任何特定功能?如果没有,为什么不尝试 WebSecurityConfigurer 用于资源处理程序,WebSecurityConfigurerAdapter 用于安全配置?

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {

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


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   
 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/css/**", "/js/**", "/image/**"").permitAll()
    }
}

【讨论】:

  • 我根据spring.io博客http.authorizeRequests() .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll();允许访问常见的静态资源位置,但我仍然无法访问它。
猜你喜欢
  • 2015-07-08
  • 2021-06-21
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
相关资源
最近更新 更多