【问题标题】:Spring 5: How to load static resources (css, js, images)Spring 5:如何加载静态资源(css、js、图片)
【发布时间】:2018-07-06 14:12:47
【问题描述】:

我正在将一个项目从 Spring 4 升级到 Spring 5,但加载静态资源不起作用。 我有我的资源 src/main/resources/static/js, src/main/resources/static/csssrc/main/resources/static/images

我在WebConfig中添加了一个ResourceHandler如下

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.job.controllers"})
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/");
    }
    // more code here
}

我的允许访问静态资源的安全配置如下

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Override 
   protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login**", "/static/**").permitAll()
   }
}

当我访问http://localhost:8080/static/css/file.css

我收到错误405 Request method 'GET' not supported

问题似乎不在安全配置中,因为它没有将我重定向到登录页面。如果我尝试像 http://localhost:8080/some-place/css/file.css 这样的非公共 URL,我会被重定向到登录页面。

问题似乎出在 ResourceHandler。

我的依赖是: spring-framework - 5.0.2.RELEASE and spring-security-5.0.0.RELEASE

其他问题中的答案都不适合我。 other-question 谢谢

【问题讨论】:

标签: spring spring-mvc


【解决方案1】:

我意识到,当我在 WebConfig 类上注释掉 @ComponentScan(basePackages = {"com.job.controllers"}) 行时,静态资源会加载。

这意味着问题出在我的一个控制器上。

映射了一个控制器方法@RequestMapping(params = "settings/view", method = RequestMethod.POST)

该映射在启动日志中显示为INFO Mapped "{[],methods=[POST],params=[settings/view]}" onto .....

这是一个不正确的映射,它正在阻止加载静态资源。

当我像这样将 'params' 更正为 'value' => @RequestMapping(value = "settings/view", method = RequestMethod.POST) 加载的静态资源。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-16
    • 2019-01-31
    • 2013-07-18
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2017-05-27
    相关资源
    最近更新 更多