我不知道 java 过滤器中 doFilter() 方法的生命周期。我想知道我是否要在方法开始时在请求中设置开始时间,有没有办法或地方在方法中设置停止时间,这会给我从请求开始到的总经过时间给出答复的时间?我已经看到了一个带有 finally 块的 doFilter() 方法,我想知道在响应中设置停止时间是否合适?
问问题
3684 次
1 回答
7
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class ResponseTimerFilter implements Filter {
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long elapsed = System.currentTimeMillis() - startTime;
String name = "servlet";
if (request instanceof HttpServletRequest) {
name = ((HttpServletRequest) request).getRequestURI();
}
config.getServletContext().log(name + " took " + elapsed + " ms");
}
}
web.xml
<filter>
<filter-name>Timing Filter</filter-name>
<filter-class>com.omh.filters.ResponseTimerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Timing Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
于 2013-04-17T03:16:25.953 回答