spring-boot - 来自 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 上)?
解决方案
尝试这个。
@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")
推荐阅读
- git - “git结帐
“删除文件,如何避免? - c# - 有没有可靠的方法来获取 Outlook 日历的事件(如添加、更新和删除)?
- regex - 正则表达式以搜索具有空间出现次数的字符串
- c# - 您必须先登录才能使用这部分 Bugzilla
- python - 字符串可以用来生成difflib.HtmlDiff().make_file的比较报告吗?
- php - Nginx + PHP-FPM:PHP-FPM 容器的 5000 端口连接被拒绝,而 9000 端口没有问题
- python - 如何在 Django 中进行分层验证?
- python - 在python中动态更改嵌套字典的值
- javascript - 在 chrome 上使用 requestAnimationFrame 每 100 毫秒调用一个函数
- python - 为什么我会收到错误消息“start_time is not defined”?