测试访问时间的Filter

今天写了一个测试访问某个资源花费多少时间的过滤器,给大家分享一下

  package com.own.filter;

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;
import javax.servlet.http.HttpServletResponse;

public class CalculateTimeFilter implements Filter {

	public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws ServletException,IOException{
		//记录请求开始的时间
		long beginTime = System.currentTimeMillis();
		//调用下一个过滤器
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		chain.doFilter(httpRequest, httpResponse);
		long endTime = System.currentTimeMillis();
		long costTime = endTime - beginTime;
		System.out.println("请求"+httpRequest.getRequestURI()+"花费了"+costTime+"毫秒");
	    //httpResponse.sendRedirect("bb.jsp");
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("filter is initialized");
	}
	
	
}


这里也可以把花费时间记录到数据库中

你可能感兴趣的:(filter)