我无法让Spring-boot项目提供静态内容。
我在src/main/resources下放置了一个名为static的文件夹。其中有一个名为images的文件夹。当我将应用程序打包并运行时,它无法找到我放在该文件夹中的图像。
我试着把静态文件放在公共、资源和META-INF/资源中,但都不起作用。
如果我jar -tvf app.jar,我可以看到文件在jar的右边文件夹:
/static/images/head.png为例,但调用:http://localhost:8080/images/head.png,我得到的是一个404
知道为什么弹簧靴找不到这个吗?(我使用1.1.4 BTW)
只是为一个老问题补充另一个答案……人们已经提到@EnableWebMvc将阻止WebMvcAutoConfiguration加载,这是负责创建静态资源处理程序的代码。还有其他一些条件也会阻止WebMvcAutoConfiguration的加载。要明白这一点,最明确的方法是查看源代码:
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java#L139-L141
在我的例子中,我包括了一个库,它有一个从WebMvcConfigurationSupport扩展的类,这是一个将阻止自动配置的条件:
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
重要的是不要从WebMvcConfigurationSupport扩展。相反,从WebMvcConfigurerAdapter扩展。
更新:正确的方法做到这一点在5。实现WebMvcConfigurer
供参考:我还注意到,如果我添加了一个糟糕的休息控制器,我可以搞砸一个完美工作的spring boot应用程序,并阻止它从静态文件夹中提供内容
@RestController
public class BadController {
@RequestMapping(method= RequestMethod.POST)
public String someMethod(@RequestParam(value="date", required=false)String dateString, Model model){
return "foo";
}
}
在本例中,在将坏控制器添加到项目后,当浏览器请求静态文件夹中可用的文件时,错误响应是'405 Method Not Allowed'。
注意,在坏控制器示例中没有映射路径。
我认为前面的回答很好地解决了这个问题。然而,我要补充的是,当你在应用程序中启用了Spring Security时,你可能必须明确地告诉Spring允许对其他静态资源目录的请求,例如“/static/fonts”。
在我的情况下,我有“/static/css”,“/static/js”,“/static/images”默认允许,但/static/fonts/**被我的Spring安全实现阻塞。
下面是我如何解决这个问题的示例。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.....
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/fonts/**").permitAll().
//other security configuration rules
}
.....
}