我通过在我的onStartup
方法中将该行放入WebApplicationInitializer.class
这是我添加的行 servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ConfigMVC.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
然后我在我的控制器中创建了这个控制器方法 GlobalExceptionHandlerController.class
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handle(NoHandlerFoundException ex) {
return "my404Page";
}
这解决了我的问题,我删除了handleResourceNotFoundException
控制器方法,GlobalExceptionHandlerController.class
因为这是不必要的,而且我还删除了ResourceNotFoundException.class
我创建的异常类