标签:缓存过滤器
缓存过滤器
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Servlet Filter implementation class CacheFilter
*/
public class CacheFilter implements Filter {
private Map<String,byte[]> map = new HashMap();//缓存
/**
* Default constructor.
*/
public CacheFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// TODO Auto-generated method stub
// place your code here
//1.得到用户请求的url
String uri = request.getRequestURI();
//2.看缓存中有没有url对应的数据
byte data[] = map.get(uri);
//3.如果缓存中有数据,直接返回
if(data != null){
response.getOutputStream().write(data);
return;
}
//4.如果没有,让目标资源执行,并捕获目标资源输出
BufferHttpResponse bufferHttpResponse = new BufferHttpResponse(response);
chain.doFilter(request, response);
byte out[] = bufferHttpResponse.getBuffer();
//5.把目标资源数据以uri为关键字保存到缓存中
map.put(uri, out);
//6.把数据输出到浏览器
response.getOutputStream().write(out);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
class BufferHttpResponse extends HttpServletResponseWrapper {
private HttpServletResponse response;
private ByteArrayOutputStream bout = new ByteArrayOutputStream();
private PrintWriter pw;
public BufferHttpResponse(HttpServletResponse response) {
super(response);
this.response = response;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(bout);
}
@Override
public PrintWriter getWriter() throws IOException {
pw = new PrintWriter(new OutputStreamWriter(bout,this.response.getCharacterEncoding()));
return pw;
}
public byte[] getBuffer() {
try {
if(pw != null){
pw.close();
}
if (bout != null)
bout.flush();
return bout.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class MyServletOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bout;
public MyServletOutputStream(ByteArrayOutputStream bout) {
this.bout = bout;
}
@Override
public void write(int arg0) throws IOException {
}
}
本文出自 “德泽无忧” 博客,谢绝转载!
标签:缓存过滤器
原文地址:http://dezewuyou.blog.51cto.com/2628602/1829014