图灵学院--Java高级架构师-互联网企业级实战VIP课程(价值6380)(qq:1324981084)
public class StaticResponse extends HttpServletResponseWrapper {
private PrintWriter pw;
public StaticResponse(HttpServletResponse response, String filepath)
throws FileNotFoundException, UnsupportedEncodingException {
super(response);
pw = new PrintWriter(filepath, "UTF-8");[使用路径创建流!当使用该流写数据时,数据会写入到指定路径的文件中。]
}
public PrintWriter getWriter[jsp页面会调用本方法获取这个流!使用它来写入页面中的数据。这些数据都写入到指定路径的页面中去了,即写入到静态页面中。]() throws IOException {
return pw;
}
public void close() throws IOException {
pw.close();
}
}
public class StaticFilter implements Filter {
private ServletContext sc;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String key = "key_" + request.getParameter("category");[获取分类参数,分类参数可能是:1,2,3,null。使用分类参数做key]
Map<String,String> map = (Map<String, String>) sc.getAttribute("pages");[在ServletContext中获取Map,首次访问这个Map不存在。]
if(map == null) {
map = new HashMap<String,String>();
sc.setAttribute("pages", map);
}[如果Map不存在,那么创建一个Map,并存放到ServletContext中,这样下次访问Map就存在了。]
if(map.containsKey(key)) {
res.sendRedirect(req.getContextPath() + "/staticPages/" + map.get(key));
return;
}[查看Map中是否存在这个key,如果存在,那么获取值,值就是这个参数对应的静态页面路径。然后直接重定向到静态页面!]
String html = key + ".html";[如果当前请求参数对应的静态页面不存在,那么就生成静态页面,首先静态页面的名称为key,容颜名为html]
String realPath = sc.getRealPath("/staticPages/" + html);[生成真实路径,下面会使用这个路径创建静态页面。]
StaticResponse sr = new StaticResponse(res, realPath);[创建自定义的response对象,传递待生成的静态页面路径]
chain.doFilter(request, sr);[放行]
sr.close();[这个方法的作用是刷新缓冲区!]
res.sendRedirect(req.getContextPath() + "/staticPages/" + html);[这时静态页面已经生成,重定向到静态页面]
map.put(key, html);[把静态页面保存到map中,下次访问时,直接从map中获取静态页面,不用再次生成。]
}
public void init(FilterConfig fConfig) throws ServletException {
this.sc = fConfig.getServletContext();
}
}