gpt4 book ai didi

Spring boot standalone tomcat HttpServletResponse 总是返回状态 200

转载 作者:行者123 更新时间:2023-11-28 23:33:07 25 4
gpt4 key购买 nike

我正在使用 spring boot 版本 1.1.8 ,我有以下拦截器拦截所有传入的 http 请求,一个功能是在 post 句柄上打印响应状态代码

public class TimingInterceptor extends HandlerInterceptorAdapter {
private static final String TIME_ATTR = "startTime";

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
request.setAttribute(TIME_ATTR, System.currentTimeMillis());
boolean hasQuery = StringUtils.isNotEmpty(request.getQueryString());
log.info("[START] method={} path={} {}{}", request.getMethod(), request.getRequestURI(),
hasQuery ? "?" : "", hasQuery ? request.getQueryString() : "");
return super.preHandle(request, response, handler);

}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
try {
long duration = System.currentTimeMillis() - (long) request.getAttribute(TIME_ATTR);

log.info("[FINISH] method={} path={} status={} [time={}] Milisec",
request.getMethod(), request.getRequestURI(), response.getStatus(), duration);
} catch (Exception e) {
log.error("Error while measuring timing", e);
}
super.postHandle(request, response, handler, modelAndView);
}

在嵌入式 tomcat 上运行时,状态符合预期,例如在这种情况下:

@RequestMapping(method = RequestMethod.GET, value = "/test")
public ResponseEntity<Void> test(HttpServletResponse response) {
return new ResponseEntity<Void>(HttpStatus.CREATED);
}

拦截器将打印 201,这是 (CREATED) 但是当在独立的 tomcat 上运行时,拦截器将打印 200 也尝试过这种方式

@RequestMapping(method = RequestMethod.GET, value = "/test")
public ResponseEntity<Void> test(HttpServletResponse response) {
response.setStatus(201);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}

但是没有成功,有什么想法是错的吗?将不胜感激!

最佳答案

这是来自 Spring Boot 的 ErrorPageFilter 包装了 HttpServletResponse。可能是一个错误。

关于Spring boot standalone tomcat HttpServletResponse 总是返回状态 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27964864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com