Search code examples
javaspring-bootspring-restcontroller

Trying to serve static content from my SpringBoot app, but it fails


I want to serve static files from my SpringBoot application. I have this very simple controller that I wish does the stuff:

@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());
   }
}

My index.html file resides in the static folder:

MyApp/
   src/
      main/
         static/index.html
         static/img/image.png

When I do a GET request with curl to http://localhost:8080 the I get response code 404 in return and the server states No mapping for GET /. I expect that the index.html file is returned.

Sending a POST request to http://localhost:8080/hello with a MyBody object as a json body works though!

What have I done wrong?

I have read this blogpost from the Spring site, but it seems quiet old since that post was published in 2013. Maybe it works different today?


Solution

  • You should NOT use EnableWebMvc in Spring Boot. See the documentation