下面是一个简单的用于记录请求的URL,请求处理时间的小例子。
在代码中设置Filter
@WebListener
public class Configurator implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) { }
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
FilterRegistration.Dynamic registration = context.addFilter("requestLogFilter", new RequestLogFilter());
registration.addMappingForUrlPatterns(null, false, "/*");
}
}
Log Filter的代码
public class RequestLogFilter implements Filter {
@Override
public void init(FilterConfig fConfig) throws ServletException { }
@Override
public void destroy() { }
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException {
Instant time = Instant.now();
//这里学习一下org.apache.commons.lang3.time.StopWatch的用法,类似于一个秒表计时器,启开,暂停,结束等
StopWatch timer = new StopWatch();
try{
timer.start();
chain.doFilter(request, response);
}finally{
//记录servlet的处理情况
timer.stop();
HttpServletRequest in = (HttpServletRequest)request;
HttpServletResponse out = (HttpServletResponse)response;
//如果是在filter之后的Servlet container(也即web container)进行中设置,检测的值为null
String length = out.getHeader("Content-Length");
if(StringUtils.isEmpty(length))
length = "-";
Ststem.out.println(in.getRemoteAddr() + " - - [" + time + "]" +
" \"" + in.getMethod() + " " + in.getRequestURI() + " " +
in.getProtocol() + "\" " + out.getStatus() + " " + length + " " + timer);
}
}
}
相关链接: 我的Professional Java for Web Applications相关文章
转载请注明原文地址: https://ju.6miu.com/read-11528.html