views:

30

answers:

1

Hi,

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

+1  A: 

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

BalusC
I might be misunderstanding, but gae doesn't care if it's user-specific data - I would just put it in a unique key like: cache.put(username+'_horses', stringOfHorses);. I think it's ok? Yeah I need to stop using the scriptlets for page generation.
Or the session ID as obtained by `session.getId()`. After all, I don't think that it's beneficial. You risk duplicating `Horse` objects in cache and you would still like to remove it from the cache when the session expires, else the cache might blow. Cache makes more sense for applicationwide data. E.g. constant values which you'd like to display in dropdowns and so on. You can also put **all** `Horse` objects in a `Map` in the cache during webapp's startup and obtain them from there instead of the DB. I in turn only question the speed of retrieving *specific* `Horse` objects from it...
BalusC