【问题标题】:Spring Customize whitelabel error - redirectSpring自定义whitelabel错误 - 重定向
【发布时间】:2020-10-25 19:33:06
【问题描述】:

我正在尝试通过在使用 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-boot spring-mvc spring-restcontroller spring-autoconfiguration


    【解决方案1】:
    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;
    

    【讨论】:

    • 此服务的 UI 是外部的,因此,我试图重定向到 UI URL,但它没有发生
    • 好吧,你应该在重定向后添加一个return 语句以使其工作。
    • 更新了答案以获得更多说明。
    • 更新和关于return语句,它只是将响应位置设置为重定向的url,但不重定向
    • 返回“重定向:”+ url;在 UI 中打印“redirect:”而不是重定向
    【解决方案2】:

    问题已解决。这个应用程序有一些使用 Spring Security 的自定义库。如果没有访问令牌,则会发生此错误。我需要探索更多的 401 错误,但现在,要处理错误,我使用带有 @RestControllerAdvice 的类并将属性 spring.mvc.throw-exception-if-no-handler-found 设置为 true 并禁用 whitelabel。

    授权成功后重定向逻辑起作用。

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2013-06-18
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多