1
我有一個Spring 4 MVC應用程序,其中有一個攔截器,用於計算請求響應週期的執行時間,我想設置一個頭,如X-Runtime
,其值爲執行時間處理時間。但是,response.setHeader
函數不起作用。當響應到達我的瀏覽器時,它被覆蓋。Spring MVC 4:攔截器無法設置響應頭
我有一個CORS過濾器,我設置請求和響應頭來啓用交叉原點請求,並且工作正常。
這裏是我的攔截器:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteTimeInterceptor.class.getName());
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
LOGGER.info("Request URL::" + request.getRequestURL().toString() + ":: Start Time=" + System.currentTimeMillis());
request.setAttribute("startTime", startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
Long startTime = (Long) request.getAttribute("startTime");
Long timeTaken = (System.currentTimeMillis() - startTime);
LOGGER.info("Request URL::" + request.getRequestURL().toString() + ":: Time Taken=" + timeTaken);
response.setHeader("X-Runtime", timeTaken.toString());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Do nothing.
}
}
我在dispatcher.xml
配置文件配置正確的攔截器。執行時間被slf4j
正確記錄,所以我可以確認攔截器本身工作正常。
任何想法爲什麼會發生這種情況?我使用WildFly(以前的JBoss)8.1作爲我的容器/應用程序服務器。