欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp首页静态化

程序员文章站 2022-07-14 09:26:45
...
应用背景: 网站首页是网站访问频度最大的页面,同样这个页面承载的信息也是最多与广泛的。而这些信息对及时行要求也不是特别高(一般一天一个更新)。这种情况下应用缓存静态化比较适合。

代码流程:

[img]http://dl.iteye.com/upload/attachment/0063/6425/fc2e4e71-0237-3258-aeab-9167dae99878.jpg[/img]


关键代码:
本代码以jsp为例,其实还可以用freemarker等模板语言,但本人认为页面静态化属于后期优化工作,目前jsp应用要比freemarker要广泛,所以jsp更具有意义。

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
//实际中这个路径会根据参数在一定规则的计算下得到,保证其唯一性
File f = new File("/htmls/test.html");
if (!f.exists())
{
//加工数据,实际中会调用service
request.setAttribute("name",
"测试");
String content = JspUtil.getHtml(request, response,
"/index.jsp");
FileUtil.save(content, "/htmls", null, "test.html");
}
StringBuffer sb = new StringBuffer();
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String str = null;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
fr.close();
br.close();
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.print(sb.toString());
out.flush();
}



public class JspUtil
{

public static String getHtml(HttpServletRequest request,
HttpServletResponse response, String jsp) throws ServletException,
IOException
{

FileCaptureResponseWrapper fileCaptureResponseWrapper = new FileCaptureResponseWrapper(response);

request.getRequestDispatcher(jsp).forward(request,
fileCaptureResponseWrapper);

return fileCaptureResponseWrapper.toString();

}

public static class FileCaptureResponseWrapper extends
HttpServletResponseWrapper
{

private CharArrayWriter writer;

public FileCaptureResponseWrapper(HttpServletResponse response)
{
super(response);
this.writer = new CharArrayWriter();
}

public PrintWriter getWriter()
{
return new PrintWriter(writer);
}

@Override
public String toString()
{

String result = writer.toString();
writer.flush();
writer.close();
return result;
}

}

}


后话:得到html代码后,可以存储到磁盘上,同样也可以应用缓存框架等工具,具体可以看具体情况而定。至于更新,可以设置时间更新,比如一天一次。同样也可以手动更新,比如编辑有一个即时更新首页的需要,这种情况最好手动更新啦。具体做法就是把存储的html数据清空就可以了!
相关标签: 企业应用