首页 > 解决方案 > Spring自定义whitelabel错误 - 重定向

问题描述

我正在尝试通过在使用 RestController 注释的类中实现错误控制器来自定义 /error。

Spring Boot 应用程序包含自动配置库,并且没有显式设置或使用 MVC。

@RequestMapping("/error")
public String handler(){
return "Error Occurred";
}

当错误状态为 401 和 404 时,上面的代码可以正常工作。

@RequestMapping("/error")
public void handler(HttpServletResponse response)
{
response.sendRedirect("http://<url>/home");
return;// edit: Even adding this statement is just setting location but not redirecting.
}

这是设置位置以响应重定向 url 但不重定向。

要求是将 /error 映射到外部 UI 页面。

现在,当我使用redirectview 或responsentity 时,处理程序中的逻辑仅在手动调用/error 并且404 不调用/error 时才有效。它只是说找不到此页面。有人可以告诉我这是因为自动配置库还是我遗漏了什么?

标签: spring-bootspring-mvcspring-restcontrollerspring-autoconfiguration

解决方案


  1. 将此条目添加到 application.properties 文件server.error.whitelabel.enabled=false。这将完全禁用白标错误页面。

  2. 自定义错误控制器

     @RequestMapping("/error")
     public String handleError(HttpServletRequest request) {
     Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    
     if (status != null) {
         Integer statusCode = Integer.valueOf(status.toString());
    
         if(statusCode == HttpStatus.NOT_FOUND.value()) {
             return "error-404";
         }
         else if(statusCode == HttpStatus.UNAUTHORIZED).value()) {
             return "error-401";
         }
     }
     return "error";
    

    }

您可以为相应的错误添加 html 页面。

示例:对于 404 错误,用户将看到 error-404.html 页面。

如果您想重定向到外部 UI,请尝试以下操作:

String redirectUrl = `https://www.yahoo.com";
return "redirect:" + redirectUrl;

推荐阅读