How to resolve 'Resource not found 404 NOT_FOUND' when running spring boot program
Problem
When we run a Spring Boot program and visit a URL as follows:
curl http://localhost:8080/admin
Sometimes, we get this error:
2021-03-02 12:32:30,208 DEBUG org.springframework.web.servlet.DispatcherServlet : GET "/home_admin", parameters={}2021-03-02 12:32:30,216 DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/]]2021-03-02 12:32:30,221 DEBUG org.springframework.web.servlet.resource.ResourceHttpRequestHandler : Resource not found2021-03-02 12:32:30,222 DEBUG org.springframework.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
Why does this error happen? The program is correct, I promise!
Environment
- Spring Boot 1.x and 2.x
The code
The TheController.java mapping code of the Spring Boot program is:
@GetMapping("/admin")public String adminHome(Authentication authentication, Model model) { model.addAttribute("username", authentication == null ? "" : authentication.getName()); model.addAttribute("products", productService.findAll()); return "home_admin";}
The structure of the project:
.└── src/ └── main/ ├── java/ │ └── com.bswen.app9/ │ └── TheController.java └── resources/ └── templates └── home_admin.html
Reason
After the adminHome
method, the controller returns a "home_admin"
view, which cannot be resolved by Spring Boot.
Solution
We should change the mapping to make it the same name as the view name:
@GetMapping("/home_admin")public String adminHome(Authentication authentication, Model model) { model.addAttribute("username", authentication == null ? "" : authentication.getName()); model.addAttribute("products", productService.findAll()); return "home_admin";}
The key point is:
@GetMapping("/home_admin")
It should have the same name as the view name:
return "home_admin";
Run the app again, and no error messages will appear. It works!
Summary
In this post, we explored how to resolve the Resource not found 404 NOT_FOUND
error in Spring Boot. The main issue arises when the URL mapping in the @GetMapping
annotation does not match the view name returned by the controller. By ensuring that these names match, we can avoid this common error. This solution is applicable to both Spring Boot 1.x and 2.x versions.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!