我无法让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)
有时候值得检查一下你是否用某个rest控制器重写了全局映射。简单的例子错误(kotlin):
@RestController("/foo")
class TrainingController {
@PostMapping
fun bazz(@RequestBody newBody: CommandDto): CommandDto = return commandDto
}
在上面的例子中,当你请求静态资源时,你会得到:
{
title: "Method Not Allowed",
status: 405,
detail: "Request method 'GET' not supported",
path: "/index.html"
}
原因可能是你想要将@PostMapping映射到/foo,但忘记了@RestController级别上的@RequestMapping注释。在这种情况下,所有请求都映射到POST,在这种情况下,您将不会收到静态内容。
我在spring boot 2.1.3中也遇到了同样的问题,说资源没有找到404。我从application .properties中删除了下面的内容。
#spring.resources.add-mappings=true
#spring.resources.static-locations=classpath:static
#spring.mvc.static-path-pattern=/**,
删除了@enableWebMVC,并删除了任何WebMvcConfigurer覆盖
@EnableWebMvc
还要确保在配置中有@EnableAutoConfiguration。
然后把所有的静态资源放到src/main/resources/static中,它就像魔术一样最终工作了。
有两件事需要考虑(Spring Boot v1.5.2.RELEASE)-
1)检查所有控制器类的@EnableWebMvc注释,如果有的话删除它
2)检查使用注释的Controller类- @RestController或@Controller。不要将Rest API和MVC行为混合在一个类中。对于MVC使用@Controller,对于REST API使用@RestController
以上两件事解决了我的问题。现在我的春季引导加载静态资源没有任何问题。
@Controller => load index.html =>加载静态文件。
@Controller
public class WelcomeController {
// inject via application.properties
@Value("${welcome.message:Hello}")
private String message = "Hello World";
@RequestMapping("/")
public String home(Map<String, Object> model) {
model.put("message", this.message);
return "index";
}
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet/less" th:href="@{/webapp/assets/theme.siberia.less}"/>
<!-- The app's logic -->
<script type="text/javascript" data-main="/webapp/app" th:src="@{/webapp/libs/require.js}"></script>
<script type="text/javascript">
require.config({
paths: { text:"/webapp/libs/text" }
});
</script>
<!-- Development only -->
<script type="text/javascript" th:src="@{/webapp/libs/less.min.js}"></script>
</head>
<body>
</body>
</html>