天天看點

動态頁面轉化為靜态頁面

1 通過filter進行對response的替換完成,
2 讓jsp輸出在指定的檔案下的靜态頁面,
3 最後又重定向到目前項目路徑下的,靜态頁面
向對方的浏覽器傳輸html檔案的相關重要代碼如下:
有關filter的代碼:
private FilterConfig config=null;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
HttpServletRequest req=(HttpServletRequest) request;//進行類型轉化
HttpServletResponse res=(HttpServletResponse) response;//進行類型轉化
String category=req.getParameter("category");//得到分類的類是第幾個
String classp=category+".html";//完成拼接
String projectPath=config.getServletContext().getRealPath("/htmls");//得到目前的項目包下的htmls的真實路徑
File html=new File(projectPath,classp);//封裝成一個檔案對象
if(html.exists()){//判斷htnl是否存在
res.sendRedirect(req.getContextPath()+"/htmls/"+classp);//重定向到制定的html下
return ;
}
//偷換respond對象
responceA responceA=new responceA(res, html.getAbsolutePath());//偷換對象
chain.doFilter(req, responceA);//放行
//重定向到目前項目路徑下的資源檔案
res.sendRedirect(req.getContextPath()+"/htmls/"+classp);


}
public void init(FilterConfig fConfig) throws ServletException {
this.config=fConfig;//将Filterconfig對象儲存到本類之中
}有關替換類的代碼:
private PrintWriter writer=null;


public responceA(HttpServletResponse response,String path) {
super(response);
try {
writer=new PrintWriter(path,"utf-8");//把輸出的路徑改成了目前磁盤下的路徑
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}


}
public PrintWriter getWriter() throws IOException {
 
return writer;//傳回磁盤下的輸出流對象,jsp會向該對象進行輸出
}