扔404并重定向到春季的自定义错误页面
问题描述:
我有下面一块异常处理程序,当找不到资源时重定向到“notfound”页面。但是,在Apache日志中,我没有看到404错误代码。有没有办法得到这个异常处理程序抛出的404错误?扔404并重定向到春季的自定义错误页面
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
request.setAttribute("message", e.getMessage());
return "forward:notfoundpage";
}
答
最好不要重定向到错误页面,而只是显示错误消息并设置错误的HTTP状态码。您可以通过在控制器处理程序方法中抛出异常来执行此操作。
你需要做那么一类把它(尽管也许你已经用你的UnknownIdentifierException做到了这一点):
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {}
在你的控制器处理方法:
throw new ResourceNotFoundException();
要设置页面在web.xml中显示一个异常:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/errors/404.jsp</location>
</error-page>
答
是:
@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
谢谢。但是,下一行不会重定向覆盖我们刚刚设置的404? – hop 2015-04-02 19:39:33
如果它将重定向 - 是的,但这里是转发http://stackoverflow.com/questions/18671463/why-do-we-use-redirect-in-spring-mvc – 2015-04-02 19:44:35
对不起亚历克斯。我的意思是前进。所以当我们使用forward时,它不会改变HTTP代码,它仍然会保持404? – hop 2015-04-02 21:22:45