我无法让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)
中配置的静态位置对/**的请求进行评估
resourceProperties。
在应用程序上添加以下内容。属性,可能是你唯一需要做的事情…
spring.resources.static-locations=classpath:/myresources/
这将覆盖默认的静态位置,即:
ResourceProperties.CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
您可能不想这样做,只需确保您的资源最终位于这些默认文件夹中的一个。
执行请求:
如果我将example.html存储在/public/example.html
然后我可以像这样访问它:
<host>/<context-path?if you have one>/example.html
如果我想要另一个uri,如<host>/<context-path>/magico/*用于类路径:/magicofiles/*中的文件,则需要更多的配置
@Configuration
class MyConfigClass implements WebMvcConfigurer
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/magico/**").addResourceLocations("/magicofiles/");
}
供参考:我还注意到,如果我添加了一个糟糕的休息控制器,我可以搞砸一个完美工作的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'。
注意,在坏控制器示例中没有映射路径。