您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring MVC如何使用Java配置和无Web.xml处理404页面未找到异常

Spring MVC如何使用Java配置和无Web.xml处理404页面未找到异常

我通过在我的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我创建的异常类

java 2022/1/1 18:14:16 有476人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶