others-how to solve 'Resource not found 404 NOT_FOUND' when running spring boot program ?
Problem
When we run a spring boot progam , 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 found
2021-03-02 12:32:30,222 DEBUG org.springframework.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
Why do 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 can not be resloved 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 has the same name as the view name:
return "home_admin";
Run the app again, No error messages ,It works!