java - 尝试从我的 SpringBoot 应用程序提供静态内容,但失败

标签 java spring-boot spring-restcontroller

我想从我的 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/

相关文章:

java - 显示安卓证书

java.lang.NoSuchMethodError : javax. servlet.ServletContext.getContextPath()Ljava/lang/String;

java - 具有多种配置的Spring Boot测试

java - @RequestBody 返回的 Marshall 对象

java - 枚举作为 Spring Boot Rest 中的请求参数

java - 在java中使用正则表达式,解析文本的各个部分

java - 在二维数组中生成世界地图

spring-boot - GCP 和 Spring logback。严重性始终是信息

java - 如何检查 REST 请求中是否包含不支持的参数?

java - Spring 启动 + REST + HATEOAS + HAL