package cn.itcast.book.web.filter;
import java.io.File;
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;
public class StaticFilter implements Filter {
private FilterConfig config;
public void destroy() {}
public void init(FilterConfig fConfig) throws ServletException {
this.config = fConfig;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
/*
?* 1. 第一次訪問時,查找請求對應(yīng)的html頁面是否存在吟逝,如果存在重定向到html
?* 2. 如果不存在,放行归露!把servlet訪問數(shù)據(jù)庫后,輸出給客戶端的數(shù)據(jù)保存到一個html文件中
?* ? 再重定向到html
?*/
/*
?* 一吠卷、獲取category參數(shù)羊瘩!
?* category有四種可能:
?* * null --> null.html
?* * 1 --> 1.html
?* * 2 --> 2.html
?* * 3 --> 3.html
?*
?* html頁面的保存路徑, htmls目錄下
?*
?* 判斷對應(yīng)的html文件是否存在要糊,如果存在,直接重定向碾盟!
?*/
String category = request.getParameter("category");
String htmlPage = category + ".html";//得到對應(yīng)的文件名稱
String htmlPath = config.getServletContext().getRealPath("/htmls");//得到文件的存放目錄
File destFile = new File(htmlPath, htmlPage);
if(destFile.exists()) {//如果文件存在
// 重定向到這個文件
res.sendRedirect(req.getContextPath() + "/htmls/" + htmlPage);
return;
}
/*
?* 二棚辽、如果html文件不存在,我們要生成html
?* 1. 放行冰肴,show.jsp會做出很多的輸出屈藐,我們要讓它別再輸出給客戶端榔组,而是輸出到我們指定的一個html文件中
?* 完成:
?* * 調(diào)包response,讓它的getWriter()與一個html文件綁定联逻,那么show.jsp的輸出就到了html文件中
?*/
StaticResponse sr = new StaticResponse(res, destFile.getAbsolutePath());
chain.doFilter(request, sr);//放行搓扯,即生成了html文件
// 這時頁面已經(jīng)存在,重定向到html文件
res.sendRedirect(req.getContextPath() + "/htmls/" + htmlPage);
}
}
/********************************************************************************************/
package cn.itcast.book.web.filter;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class StaticResponse extends HttpServletResponseWrapper {
private PrintWriter pw;
/**
?* String path:html文件路徑包归!
?* @param response
?* @param path
?* @throws UnsupportedEncodingException
?* @throws FileNotFoundException
?*/
public StaticResponse(HttpServletResponse response, String path)
throws FileNotFoundException, UnsupportedEncodingException {
super(response);
// 創(chuàng)建一個與html文件路徑在一起的流對象
pw = new PrintWriter(path, "utf-8");
}
public PrintWriter getWriter() {
// 返回一個與html綁定在一起的printWriter對象
// jsp會使用它進行輸出锨推,這樣數(shù)據(jù)都輸出到html文件了。
return pw;
}
}