我正在使用Spring boot版本1.1.8,我有以下拦截器拦截所有传入的超文本传输协议请求,一个功能是在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(已创建),但在独立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
。可能是bug。