春季5:如何加载静态资源(css,js,图像)

时间:2018-07-06 14:12:48

标签: spring spring-mvc

我正在将项目从Spring 4升级到Spring 5,但是无法加载静态资源。 我有我的资源     src/main/resources/static/js,     src/main/resources/static/css和     src/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 谢谢

1 个答案:

答案 0 :(得分:0)

我意识到,当我注释掉printf("..., Core: %2d\n", coreN); 类上的@ComponentScan(basePackages = {"com.job.controllers"})行时,将加载静态资源。

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

已映射一个控制器方法WebConfig

该映射在启动日志中显示为@RequestMapping(params = "settings/view", method = RequestMethod.POST)

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

当我像这样=> INFO Mapped "{[],methods=[POST],params=[settings/view]}" onto .....将'params'改成'value'时,加载的静态资源。

谢谢