缓存页面的内容? [英] Caching contents of a page?

查看:85
本文介绍了缓存页面的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成的页面内容如下:

  // index.jsp 
<%
列出< Horse> horses = database.getHorses();
(马匹:马){
%>
< div><%= it.getName()%>< / div>
<%
}
%>

有可能在jsp文件末尾抓取整个页面内容,并将其转储到一个字符串,如:

  String page = this.getPrintWriter()。toString(); 

我只是好奇这是否可能。我可能会尝试将页面缓存为字符串,但需要重写我的页面生成,以便在一个StringBuilder中构建所有内容,例如:

  StringBuilder sb = new StringBuilder(); 
sb.append(< div>); sb.append(it.getName()); sb.append( < / DIV> 中);
...
<%= sb.toString()%>
String cached = sb.toString();

谢谢

解决方案 div>

由于它是用户特定的数据,因此您不能使用 GAE的memcache 。它是一个应用程序范围的缓存。我只是将它存储在会话范围中。

  HttpSession session = request.getSession(); 
列表< Horse>马匹=(List< Horse>)session.getAttribute(马匹);
if(horses == null){
horses = database.getHorses();
session.setAttribute(马,马);
}

也就是说,尽量避免使用 scriptlets 作为尽可能多。以上完全可以在Servlet类中完成,您可以使用JSTL c:forEach 显示它们,如下所示:

 < c:forEach items =$ {horses}var =horse> 
< div> $ {horse.name}< / div>
< / c:forEach>

捕获生成的页面内容不能通过调用 PrintWriter#toString () StringBuilder 这个想法很有趣,但它确实不值得。缓存动态内容对于您提及的目的几乎没有什么好处。



在这种情况下,您可以对页面缓存做些什么,只是为了利用webbrowser的默认任务缓存GET请求。



另见




I'm generating page content like:

// index.jsp
<%
    List<Horse> horses = database.getHorses();
    for (Horse it : horses) {
        %>
        <div><%= it.getName() %></div>
       <%
    }
%>

is it possible to grab the entire page content at the end of the jsp file, and dump it into a String, like:

String page = this.getPrintWriter().toString();

I'm just curious if this is possible. I might try caching the page as a String, but would need to rewrite my page generation to build everything in one StringBuilder like:

StringBuilder sb = new StringBuilder();
sb.append("<div>"); sb.append(it.getName()); sb.append("</div>");
...
<%= sb.toString() %>
String cached = sb.toString();

Thanks

解决方案

Since it's user-specific data, you can't use GAE's memcache for this. It's an application wide cache. I'd just store it in the session scope.

HttpSession session = request.getSession();
List<Horse> horses = (List<Horse>) session.getAttribute("horses");
if (horses == null) {
    horses = database.getHorses();
    session.setAttribute("horses", horses);
}

That said, try to avoid using scriptlets as much as possible. The above can perfectly be done in a Servlet class and you can display them using JSTL c:forEach as follows:

<c:forEach items="${horses}" var="horse">
    <div>${horse.name}</div>
</c:forEach>

Capturing generated page content can't be done by simply calling PrintWriter#toString(). The StringBuilder idea is funny, but it's really not worth it. Caching dynamic content has very little benefits for the purposes as you mention.

Best what you in this case can do with regard to page caching is just to leverage the webbrowser's default task to cache GET requests.

See also

这篇关于缓存页面的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆