我有下面的异常处理程序,当找不到资源时,它会重定向到“notfound”页面。但是,在 apache 日志中,我没有看到 404 错误代码。有什么办法可以让这个异常处理程序抛出404错误吗?
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
request.setAttribute("message", e.getMessage());
return "forward:notfoundpage";
}
最佳答案
是的:
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request, final HttpServletResponse response)
{ response.setStatus(404);
request.setAttribute("message", e.getMessage());
return "forward:notfoundpage";
}
另一种方法是使用特殊注释来标记异常:
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order") // 404
public class UnknownIdentifierException extends RuntimeException {
// ...
}
另一种方法是在处理程序本身的注释中指定错误代码:
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Data integrity violation")
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
///
这是有关主题的长博文:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
关于java - Spring中抛出404并重定向到自定义错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29419026/