我通过在我的
onStartup方法中将该行放入
WebApplicationInitializer.class
这是我添加的行
servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");这就是我添加的新行的完整方法的外观
@Overridepublic 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我创建的异常类



