我正在将一个项目从 Spring 4 升级到 Spring 5,但加载静态资源不起作用。 我的资源在src/main/resources/static/js
,src/main/resources/static/css
和src/main/resources/static/images
我在WebConfig中添加了一个资源处理程序,如下所示
@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,我会被重定向到登录页面。
问题似乎出在资源处理程序中。
我的依赖项是:spring-framework - 5.0.2.RELEASE and spring-security-5.0.0.RELEASE
其他问题中的任何答案都不适合我。 其他问题 谢谢
我意识到,当我注释掉WebConfig
类上的@ComponentScan(basePackages = {"com.job.controllers"})
行时,静态资源会加载。
这意味着问题出在我的一个控制器上。
映射了一种控制器方法@RequestMapping(params = "settings/view", method = RequestMethod.POST)
该映射在启动日志中显示为INFO Mapped "{[],methods=[POST],params=[settings/view]}" onto .....
这是一个不正确的映射,它阻止了静态资源的加载。
当我像这样将"参数"更正为"值"时 =>@RequestMapping(value = "settings/view", method = RequestMethod.POST)
加载了静态资源。
谢谢