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

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

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

相关文章:

java - 创建 "good"SecureRandom 的最佳方法是什么?

java - 在请求负载中设置字符串列表

spring-mvc - Spring MVC Portlet Eclipse 插件

java - 如何分别获取名词、动词、形容词同义词集?

java - Spring Boot 对于 Java Web 应用程序有哪些缺点?

spring - -Dlogback.configurationFile=logback.xml 在运行 Spring-Boot 时被忽略

java - Spring Boot 测试@Transactional 不保存

java - 自动检测 Jackson for Spring

java - Spring : ClassNotFound exception

java - 在 Eclipse 中启动时自动导入添加到项目路径中的新 Java 类