日期:2014-05-16  浏览次数:20393 次

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

代码流程:




关键代码:
本代码以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数据清空就可以了!