1.示例:下载计数过滤器
2.描述:可以通过Filter实现一个过滤器,用于统计不同资源被访问的次数,为了简单起见,将资源访问记录以键值对的方式保存在downloadCountLog.text中
3.源代码:
package filter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
@WebFilter(filterName="DownloadCountFilter", urlPatterns={"/*"},
initParams={
@WebInitParam(name="fileName", value="downloadCountLog.txt"),
@WebInitParam(name="path", value="E:/")
}
)
public class DownloadCountFilter implements Filter {
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private File logFile;
private Properties downloadCountLog;
public void init(FilterConfig filterConfig) throws ServletException {
String fileName = filterConfig.getInitParameter("fileName");
String path = filterConfig.getInitParameter("path");
logFile = new File(path, fileName);
if(!logFile.exists()){
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
downloadCountLog = new Properties();
try {
downloadCountLog.load(new FileReader(logFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
/*
* 将请求的URI查找到,然后取出对应的数值
* 如果该值不存在,这创建
* 如果存在,则加1,然后在保存
* */
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
final String uri = httpServletRequest.getRequestURI();
executorService.execute(new Runnable(){
public void run() {
String number = downloadCountLog.getProperty("uri");
if(number != null){
int count = 0;
count = Integer.parseInt(number);
count++;
downloadCountLog.setProperty(uri, Integer.toString(count));
}else{
downloadCountLog.setProperty(uri, "1");
}
try {
downloadCountLog.store(new FileWriter(logFile), "");
} catch (IOException e) {
e.printStackTrace();
}
}
});
filterChain.doFilter(request, response);
}
public void destroy() {
if(executorService != null){
executorService.shutdown();
}
}
}