【发布时间】:2020-02-09 16:15:07
【问题描述】:
我想从我的 SpringBoot 应用程序中提供静态文件。我有一个非常简单的控制器,我希望它能做这些事情:
@EnableWebMvc
@RestController
public class MyRestController implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static")
.addResourceLocations("file:/static");
}
@PostMapping(path = "/hello")
public MyResponse hello(@RequestBody() MyBody body,
HttpServletRequest request) {
return new MyResponse("Hello " + request.getRemoteAddr());
}
}
我的 index.html 文件位于 static 文件夹中:
MyApp/
src/
main/
static/index.html
static/img/image.png
当我使用 curl 向 http://localhost:8080 发出 GET 请求时,我得到响应代码 404 作为回报,服务器状态为 No mapping for GET /。
我希望返回 index.html 文件。
不过,使用 MyBody 对象作为 json 主体向 http://localhost:8080/hello 发送 POST 请求是可行的!
我做错了什么?
我从 Spring 网站上阅读了这个 blogpost,但自从该帖子于 2013 年发布以来,它似乎已经过时了。也许它今天的工作方式有所不同?
【问题讨论】:
-
你不应该在 Spring Boot 中使用 EnableWebMvc。 docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…, docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…
-
谢谢!这就是问题所在!如果您将其发布为答案,我会将其标记为正确。
标签: java spring-boot spring-restcontroller