Sharing HTTP Session between Web applications in an EAR

One of the new features of WildFly 9 is the ability to share the HTTP Session between applications which are part of the same Enterprise Archive. (This feature is described in https://issues.jboss.org/browse/WFLY-1891 )

Undertow allows you to share sessions between wars in an ear, if it is explicitly configured to do so. Note that if you use this feature your applications may not be portable, as this is not a standard Servlet feature, although it’s available in other vendors like Websphere and Oracle Weblogic.

Let’s see an example application which consists of two Web applications: webapp1 and webapp2, bundled into one EAR archive:

wildfly 9 tutorial

As simple test, both our webapplications will include an index.jsp page which adds one random attribute to the session and dumps the content of the HttpSession:

<%
session.setAttribute(java.util.UUID.randomUUID().toString(), new java.util.Date().toString());

 
java.util.Enumeration enames = session.getAttributeNames();
while (enames.hasMoreElements()) {
   String key = (String) enames.nextElement();
   String value = "" + session.getAttribute(key);
   out.println(key + " - " + value); 
}

%>

HttpSession sharing is not enabled by default, we need to include a jboss-all.xml file in the META-INF folder of the EAR file, including a shared-session-config element within it:

<jboss umlns="urn:jboss:1.0">
    <shared-session-config xmlns="urn:jboss:shared-session-config:2.0">
        <session-config>
            <cookie-config>
                <path>/</path>
            </cookie-config>
        </session-config>
    </shared-session-config>
</jboss>

Now if you try to switch from one Web application to another you will see that the HttpSession is correctly maintained across the two Web applications.

If you want to check the full list of attributes you can apply, check the XSD file: https://github.com/wildfly/wildfly/blob/main/undertow/src/main/resources/schema/shared-session-config_2_0.xsd

Found the article helpful? if so please follow us on Socials