1.日志记录简介
记录日志也是Filter擅长的工作之一。在request之前与之后都可以记录日志。该日志记录Filter使用apache的日志工具记录日志,记录客户的IP地址,访问的URL以及系哦啊好的时间。apache的commons-logging的好处是可以自由配置,弹性大,日志Filter的代码如下:
package com.wang.indentity;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Servlet Filter implementation class myFilter
*/
public class logFilter implements Filter {
private Log log = LogFactory.getLog(getClass());//log对象
private String filterName;
public logFilter() {
System.out.println("11111111111111");
// TODO Auto-generated constructor stub
}
public void destroy() {
log.info("关闭Filter:"+filterName);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String referer = req.getHeader("referer");
long startTime = System.currentTimeMillis();
String requestUrl = req.getRequestURI();
requestUrl = req.getQueryString() == null ?requestUrl:(requestUrl+"?"+req.getQueryString());//所有的地址栏参数
chain.doFilter(req, res);
long endTime = System.currentTimeMillis();
log.info(request.getRemoteAddr()+"访问了"+requestUrl+",=总用时"+(endTime-startTime)+"毫秒。");
this.destroy();
}
public void init(FilterConfig fConfig) throws ServletException {
filterName = fConfig.getFilterName();//获取Filter名称
log.info("启动Filter:"+filterName);
}
}
注意:日志Filter的好处是可拆卸。如果不再需要记录日志,只需要将Filter配置注释掉即可。