If there is no path corresponding to Servlet mapping in spring-mvc, the following warning will appear in the log. In this case, throw an exception on the spring side and catch it. This will handle the 404 (using spring instead of web.xml).
[org.springframework.web.servlet.PageNotFound](default task-2) No mapping found for HTTP request with URI [/xxxx] in DispatcherServlet with name 'dispatcher'
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebMVCApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
Class<?>[] configurations = {AppConfiguration.class};
return configurations;
}
@Override
protected Class<?>[] getServletConfigClasses() {
Class<?>[] configs = {};
return configs;
}
@Override
protected String[] getServletMappings() {
String[] mappings = {"/"};
return mappings;
}
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
DispatcherServlet dispatcherServlet = (DispatcherServlet)super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
}
By setting setThrowExceptionIfNoHandlerFound to true, an exception will be thrown if the handler corresponding to the request is not found.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
@RestControllerAdvice
public class NoHandlerFoundControllerAdvice {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<String> handleNoHandlerFoundException(NoHandlerFoundException ex) {
return new ResponseEntity<>("not found", HttpStatus.NOT_FOUND);
}
}
Create a class that assigns ControllerAdvice (or ControllerAdvice) to describe exception handling common to multiple controllers. Since I set spring to throw NoHandlerFoundException if there is no handler corresponding to the path, specify this in ExceptionHandler.
Recommended Posts