我希望在doFilter()
函數完成運行後添加HTTP標頭。在doFilter後更新響應
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
try {
chain.doFilter(request, httpResp);
} finally {
httpResp.setHeader("ADD A HEADER: ", "HEADER");
}
}
看來,doFilter
刷新響應。
UPDATE:
感謝。觀看IgorMadjeric和richardtz答案後,我決定嘗試響應包裝:
這是包裝:
public class BufferedHttpServletResponse extends HttpServletResponseWrapper {
public BufferedHttpServletResponse(HttpServletResponse response) {
super(response);
}
public void flushBuffer() {
System.out.println("flush");
}
}
這是更改後的代碼:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
try {
BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse(httpResp);
chain.doFilter(request, bufferedResponse);
} finally {
bufferedResponse.setHeader("ADD A HEADER: ", "HEADER");
}
}
仍不工作。我做錯什麼了嗎?
爲什麼你需要在'doFilter()'後執行它? – axtavt
我想添加性能數據,它似乎是正確的地方做到這一點。 –
我有添加性能信息的類似問題。它可能取決於容器何時提交響應,並且您可能無法控制它。我最終做的是將這些信息添加到html響應中(這是我生成的html)到響應的主體。此外,只有在請求中包含某些參數時纔會生成性能信息。 – richardtz