我想从我的 SpringBoot 应用程序提供静态文件。我有一个非常简单的 Controller ,我希望它能够完成以下任务:
@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 作为返回,并且服务器状态 没有 GET/的映射
。
我期望返回index.html 文件。
使用 MyBody
对象作为 json 正文向 http://localhost:8080/hello
发送 POST 请求是可行的!
我做错了什么?
我读过这篇文章blogpost来自 Spring 网站,但自从该帖子于 2013 年发布以来,它似乎已经很老了。也许今天它的工作方式有所不同?
最佳答案
Spring Boot Documentation 中提到了这一点,在spring mvc部分下可以使用WebMvcConfigurer,但不需要做@EnableWebMvc
所以你应该删除@EnableWebMvc注释!
//@EnableWebMvc Remove this
@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());
}
}
关于java - 尝试从我的 SpringBoot 应用程序提供静态内容,但失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58353039/