【问题标题】:Throw 404 and redirect to a custom error page in Spring抛出 404 并重定向到 Spring 中的自定义错误页面
【发布时间】:2015-06-07 18:24:00
【问题描述】:

我有以下异常处理程序,当找不到资源时重定向到“未找到”页面。但是,在 apache 日志中,我没有看到 404 错误代码。有没有办法让这个异常处理程序抛出 404 错误?

@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException e, final HttpServletRequest request)
{
    request.setAttribute("message", e.getMessage());
    return "forward:notfoundpage";
}

【问题讨论】:

    标签: java spring spring-mvc jakarta-ee http-status-code-404


    【解决方案1】:

    是的:

    @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吗?
    • 如果是重定向 - 是的,但这里是转发 stackoverflow.com/questions/18671463/…
    • 对不起,亚历克斯。我的意思是向前。那么当我们使用forward时,它不会改变HTTP代码,仍然会保持404?
    【解决方案2】:

    最好不要重定向到错误页面,而只是显示错误消息并设置错误 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>
    

    【讨论】:

      猜你喜欢
      • 2015-08-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      相关资源
      最近更新 更多