Spring启动独立tomcat HttpServletResponse总是返回状态200

时间:2015-01-15 13:47:19

标签: spring spring-mvc tomcat spring-boot http-status-codes

我使用的是Spring引导版1.1.8,我有以下拦截器拦截所有传入的http请求,一个功能就是在帖子句柄上打印响应状态码

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);
}

但没有成功,任何想法都有什么不对?我将非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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