java - 使用 ErrorController 处理 http 错误
问题描述
我正在使用带有 AuthenticationEntryPoint 的 httpBasic 来验证此人是否已通过身份验证。我想通过 ErrorOcntroller 接口发送自定义错误页面。而不是仅仅返回一个字符串。
这是我的代码:
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
response.response.sendRedirect("/error");
}
我的错误控制器类
@Controller
public class RequestErrorController implements ErrorController {
private static final Logger log = LoggerFactory.getLogger(RequestErrorController.class);
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
//log.error("Error 404 generated for this request ->"+ request.getRequestURI());
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
if(statusCode == HttpStatus.UNAUTHORIZED.value()) {
return "error-401";
}
if(statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404";
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error-403";
}
else if(statusCode == HttpStatus.BAD_REQUEST.value()) {
return "The request did not match any end-point. Please revise the request signature and parameters type. ";
}
// on va rajouter bad request vue que 500 est deja la
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
问题是它根本没有到达这个控制器。
我已经对我的代码进行了更新,最后到达了控制器。现在的问题是,它正在寻找 freemake 模板:
2021-08-06 18:03:42,240 INFO [http-nio-8080-exec-2] c.n.j.A.RequestInterceptor [RequestInterceptor.java:122] returning true
0 [http-nio-8080-exec-2] DEBUG freemarker.cache - Couldn't find template in cache for "error.ftlh"("en_US", UTF-8, parsed); will try to load it.
2 [http-nio-8080-exec-2] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("error_en_US.ftlh"): Not found
3 [http-nio-8080-exec-2] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("error_en.ftlh"): Not found
3 [http-nio-8080-exec-2] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("error.ftlh"): Not found
2021-08-06 18:03:42,272 DEBUG [http-nio-8080-exec-2] o.s.w.f.CommonsRequestLoggingFilter [CommonsRequestLoggingFilter.java:55] REQUEST DATA : GET /error]
解决方案
我发现了一个类似的堆栈讨论 https://stackoverflow.com/a/26221980/16571215
还有另一种似乎很有希望的解决方案。
推荐阅读
- scala - 如何从 spark scala 中的数据框中找到短语计数?
- spring-boot - 如何将grpc与spring boot一起使用
- c# - Windows 10 UWP App:上传大文件最简单的地方?
- python - 在熊猫数据框中的日期时间列中查找时隙数
- python-3.x - 在 Python 3.x 中创建复古主题的加载屏幕
- amazon-web-services - SNS 消息是否分散到 SQS 队列以保持顺序?
- jboss - 在哪里可以找到更大尺寸的 drools 文档的铁路图
- java - 改进一个 java soap 客户端
- python - Pyserial 无法将所有字符发送到 arduino,但可以在另一个 PC 终端上发送
- c++ - c++类分配动态数组失败(内存泄漏)