From a FreeMarker template in a Java EE web application, I need to access the sessionID (i.e. HttpSession.getId()). Long story short, it’s being passed to an outside analytics provider so they can build reports about what users do during their browsing session.
Obviously, I just add the session ID to the model object which gets passed to FreeMarker. However, this application is a bit of a mess… one FreeMarker template may be used by multiple controllers passing various model objects. For maintainability, it would be far easier if I could just access the session ID from the FreeMaker template without having to change all those model classes.
I’ve found FreeMarker documentation referencing “application”, “session”, and “request” scope. However, this format does not return a value:
${Session.id}
I suspect “scope attributes” doesn’t include all getter methods on the HttpSession object (such as getId())… but rather just those values which can be fetched from HttpSession.getAttribute().
Is there an easy way to access the Java EE session ID from a FreeMarker template, without having to explicitly pass it through the model object?
You can put it in the model before rendering the template.
Normally you can put the
requestobject in the model in some base method, which is invoked when rendering all templates. That way all templates will have the request, which you need anyway. Then you access the session via the request object. That’s what we’ve done, and it works fine.