gpt4 book ai didi

java - Spring中抛出404并重定向到自定义错误页面

转载 作者:行者123 更新时间:2023-11-30 08:17:43 24 4
gpt4 key购买 nike

我有下面的异常处理程序,当找不到资源时,它会重定向到“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com