LogFilter
(一)Filter
在Java EE中,Filter是一个可以将请求和响应的头部或内容进行转换的一个对象.包括
(1)认证Filter
(2)日志和审核Filter
(3)图片转换Filter
(4)数据压缩Filter
(5)密码Filter
(6)令牌Filter
(7)触发资源访问事件的Filter
(8)XSLT Filter
(9)媒体类型链Filter
Filter可以执行的主要任务如下:
1. 查询请求,并采取相应的行动
2. 阻止任何深层次的请求-响应.
3.修改请求和响应的头和数据.
Filter的API由Filter,FilterChain,FilterConfig定义.Filter类有三个方法,init(),destory()以及定义Filter功能的doFilter()
(二)定义使用
1.通过web.xml定义
2.javad代码中,可以通过实现一个Filter接口来定义一个Filter.
3.使用@webFilter注释在web应用程序中定义一个过滤器.
具体定义方法参照 https://blog.csdn.net/flowingflying/article/details/60956507
(三)LogFilter
记录客户IP ,访问URI 以及消耗时间
package com.helloweenvsfei.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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class LogFilter implements Filter {
private Log log = LogFactory.getLog(this.getClass());
private String filterName;
//定义
public void init(FilterConfig config) throws ServletException {
// 获取 Filter 的 name,配置在 web.xml 中
filterName = config.getFilterName();
log.info("启动 Filter: " + filterName);
}
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
long startTime = System.currentTimeMillis();
String requestURI = request.getRequestURI();
//获取请求需要的URI
requestURI = request.getQueryString() == null ? requestURI : (requestURI + "?" + request.getQueryString());
//链接至下一个Filter
chain.doFilter(request, response);
long endTime = System.currentTimeMillis();
log.info(request.getRemoteAddr() + " 访问了 " + requestURI + ", 总用时 "
+ (endTime - startTime) + " 毫秒。");
}
//销毁
public void destroy() {
log.info("关闭 Filter: " + filterName);
}
}
源代码:https://blog.csdn.net/flowingflying/article/details/60959618