前段時間做自己社區的論壇,在jive的基礎上做一個頁面顯示所有論壇的帖子,可以稱之為總版,模仿Forum類的接口做個SuperForum並且實現Cachable,不過因為這個頁面刷新量比較大,雖然被Cache了,我還是想辦法進行頁面的緩存,感覺用jsp產生的html靜態內容當緩存,頁面訪問速度應該有所提高。 首先想到的一種辦法,是采用java.net的URLConnection把服務器上的jsp抓過來做緩存,不過我覺得這樣做太見外了,自己服務器上的東西,為何要用HTTP去訪問.於是想另外一個辦法,把jsp的out對象的輸出控制到自己希望的地方.比如輸出到靜態文件,又或者保存成全局的字符串變量.這樣的話,浏覽就不需要執行jsp,只是浏覽該html了.僅僅在數據有更新的時候進行一次update操作,把jsp重新輸出為html.
我覺得,浏覽事件比數據插入或更新發生的次數多的時候.不妨試試這個辦法來提高頁面訪問速度.
整件事情有點像把jsp當作模板,生成靜態的html頁面.
將如下代碼寫入web-xml
<filter>
<filter-name>FileCaptureFilter</filter-name>
<filter-class>com.junjing.filter.FileCaptureFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FileCaptureFilter</filter-name>
<url-pattern>/latest.jsp</url-pattern>
</filter-mapping>
latest.jsp是我要cache的頁面
java源碼代碼如下
/** * START File FileCaptureFilter.java */
package com.junjing.filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FileCaptureFilter implements Filter
{
private String protDirPath;
public void init(FilterConfig filterConfig)
throws ServletException
{
protDirPath = filterConfig.getServletContext().getRealPath("/");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException, ServletException
{
String fileName = protDirPath + "forum/lastest.html";
PrintWriter out = response.getWriter();
FileCaptureResponseWrapper responseWrapper = new FileCaptureResponseWrapper((HttpServletResponse)response);
chain.doFilter(request, responseWrapper);
// fill responseWrapper up
String html = responseWrapper.toString();
//得到的html頁面結果字符串
// responseWrapper.writeFile(fileName);
// dump the contents 寫成html文件,也可以保存在內存
//responseWrapper.writeResponse( out );
// back to browser
//responseWrapper.sendRedirect("lastestThread.jsp");
}
public void destroy() {}
}
/** * END File FileCaptureFilter.java */
/** * START File FileCaptureResponseWrapper.java */
package com.junjing.filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FileCaptureResponseWrapper
extends HttpServletResponseWrapper
{
private CharArrayWriter output;
public String toString()
{
return output.toString();
}
public FileCaptureResponseWrapper(HttpServletResponse response)
{
super(response);
output = new CharArrayWriter();
}
public PrintWriter getWriter()
{
return new PrintWriter(output);
}
public void writeFile(String fileName)
throws IOException
{
FileWriter fw = new FileWriter(fileName);
fw.write( output.toCharArray() );
fw.close();
}
public void writeResponse(PrintWriter out)
{
out.print( output.toCharArray() );
}
}
/** * END File FileCaptureResponseWrapper.java */