Java for Web学习笔记(四一):Filter(3)用于Log

本文介绍了一个使用Java编写的简单示例,通过配置过滤器来记录HTTP请求的URL及请求处理时间。该过滤器利用了StopWatch类进行时间测量,并在处理完成后打印相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是一个简单的用于记录请求的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相关文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值