首页 > 解决方案 > 来自 ErrorController 的 Spring 重定向

问题描述

我有许多通用错误页面,这些页面被多个应用程序使用,而不是我可以控制的应用程序。我想配置 Spring Boot 错误控制器以重定向到这些页面之一。不幸的是,它不起作用。

例如。

  @Controller  
  public class MyCustomErrorController implements ErrorController {

    @GetMapping(value = "/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 "redirect:https://www.example.com/error-404";
        }
      }

      return "redirect:https://www.example.com/error-500";
    }

    @Override
    public String getErrorPath() {
      return "/error";
    }
  }

例如,如果我故意输入错误的 URL,我可以看到响应的 Location 标头带有我期望的 404 URL,但浏览器实际上并没有重定向。如果可以从自定义 ErrorController 中进行重定向,有什么想法吗?

这可能是因为我试图从 localhost 进行测试,而 Strict-Transport-Security 忽略了响应 Location 标头值(位于 FQDN 上)?

标签: spring-bootspring-mvc

解决方案


尝试这个。

  @Controller  
  public class MyCustomErrorController implements ErrorController {

    @GetMapping(value = "/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 "redirect:/error-404"; //remove your https://www.example.com
        }
      }

      return "redirect:/error-500";
    }

    @Override
    public String getErrorPath() {
      return "/error";
    }
  }

**编辑**
更改 url 映射并重试:
error-404 -> error/404
error-500 -> error/500

@Controller  
  public class MyCustomErrorController implements ErrorController {

    @GetMapping(value = "/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 "redirect:/error/404"; //remove your https://www.example.com
        }
      }

      return "redirect:/error/500";
    }

    @Override
    public String getErrorPath() {
      return "/error";
    }
  }  

错误/404

@GetMapping("/error/404")

错误/500

@GetMapping("/error/500")

推荐阅读