Is it possible to evaluate a JSP only once per session and cache it afterwards?

My site has a navigation menu that is dynamically built as a separate JSP and is included in most pages via <jsp:include />

. The content and style of the menu determines which pages the user makes and does not have access to.

The set of available pages is retrieved from the database when the user logs on, not during a session. Therefore, there is no need to reevaluate the navigation menu code every time the user requests a page. Is there a simple way to generate markup from JSP only once per session and cache / reuse it during session?

+2


a source to share


2 answers


A similar approach, but using JSTL and not script code:



<c:if test="${empty menuContents}">
  <c:set var="menuContents" scope="session">
    Render the menu here...
  </c:set>
</c:if>
<c:out value="${menuContents}" escapeXml="false"/>

      

+3


a source


Here's a JSP tag file that should do what you want, untested.

<%@tag description="Caches the named content once per session" pageEncoding="UTF-8"%>

<%@attribute name="name"%>

<%
String value = (String)request.getSession().getAttribute(name);

if (value == null) {
%>
<jsp:doBody var="jspBody"/>
<%
    value = jspContext.getAttribute("jspBody", PageContext.PAGE_SCOPE);
    request.getSession().setAttribute(name, value);
}
jspContext.setAttribute("value", value);
%>
${value}

      



To use it, you would do something like:

<t:doonce name="navigation">
    <jsp:include page="nav.jsp"/>
</t:doonce>

      

+1


a source







All Articles