Spring Boot In Action: 404 not found.

Tram Ho

I. Introduction

The scenario that occurs is described as follows.

First you have a Spring Application with the following directory structure:

image.png

And successfully run ready on port 8487: image.png

However, when you make an API call, the HTTP response status is 404?

image.png

II. Problem analysis

We want to know why the 404 error occurs, we must first visualize the flow of an HTTP request executing in a Spring Boot application.

image.png

When Spring Boot application receives an HTTP request, there is a guy called DispatcherServlet that will dispatch these requests to the respective Controllers. After finding the Controller will have to find a handler method that can handle that request. If a suitable handler method is found, the DispatcherServlet will call the handler method and return the response.

Handler method here is an annotated method with @RequestMapping annotation or @GetMapping annotation with HTTP request method (GET/POST..) and specific path.

However, in order for a request to be called into the application, Spring Boot needs some pre-processing steps in the application startup process such as initHandlerMethods . The initHandlerMethods method is responsible for initializing all handler methods in Spring Boot.

image.png

image.png

This method will initially look for beans in the ApplicationContext annotated with the @Controller annotation or containing the @RequestMapping annotation. At this point, if we pay attention, we will discover that the cause of the above 404 error is _404Controller bean not found and this is the culprit.

image.png

But we won’t just stop the analysis there, after the initHandlerMethods method finds a bean that satisfies the requirements like @Controller / @RestController .. then for each bean found, the method goes on to find annotated methods with @ RequestMapping annotation and add it to registry to use.

image.png

image.png

image.png

image.png

Callstack

After completing the startup application and initHandlerMethods, we will proceed to plug in the debugging point in the controller and call the API to see how Spring Boot receives and processes the HTTP request.

image.png

image.png

Callstack:

References

===

Thanks for reading.

Share the news now

Source : Viblo