使用Spring控制器处理错误404

我使用@ExceptionHandler来处理我的Web应用程序抛出的exception,在我的情况下,我的应用程序返回带有HTTP status JSON响应,以便对客户端进行错误响应。

但是,我试图弄清楚如何处理error 404以返回类似的JSON响应,就像@ExceptionHandler处理的响应一样

更新:

我的意思是,当访问不存在的URL时

最简单的方法是使用以下方法:

 @ExceptionHandler(Throwable.class) public String handleAnyException(Throwable ex, HttpServletRequest request) { return ClassUtils.getShortName(ex.getClass()); } 

如果URL在DispatcherServlet的范围内,则此方法将捕获由错误输入或其他任何内容引起的任何404,但如果键入的URL超出DispatcherServlet的URL映射,则您必须使用:

  404 /404error.html  

要么

提供“/”映射到DispatcherServlet映射URL,以便处理特定服务器实例的所有映射。

我使用spring 4.0和java配置。 我的工作代码是:

 @ControllerAdvice public class MyExceptionController { @ExceptionHandler(NoHandlerFoundException.class) public ModelAndView handleError404(HttpServletRequest request, Exception e) { ModelAndView mav = new ModelAndView("/404"); mav.addObject("exception", e); //mav.addObject("errorcode", "404"); return mav; } } 

在JSP中:

  

HTTP Status 404 - Page Not Found

The page you requested is not available. You might try returning to the ">home page.

对于Init param配置:

 public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override public void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); } } 

或者通过xml:

  rest-dispatcher org.springframework.web.servlet.DispatcherServlet  throwExceptionIfNoHandlerFound true   

另请参见: Spring MVC Spring安全性和error handling

使用spring> 3.0使用@ResponseStatus

  @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { ... } @Controller public class MyController { @RequestMapping..... public void handleCall() { if (isFound()) { // do some stuff } else { throw new ResourceNotFoundException(); } } } 
 public final class ResourceNotFoundException extends RuntimeException { } @ControllerAdvice public class AppExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleNotFound() { return "404"; } } 

只需定义一个Exception,一个ExceptionHandler,从业务代码控制器中抛出Exception。

您可以使用servlet标准方式来处理404错误。 在web.xml添加以下代码

  404 /404error.html