This guide describes how to configure Spring Session to transparently leverage Pivotal GemFire to back a web application’s HttpSession using XML Configuration.

Updating Dependencies

Before using Spring Session, you must ensure that the required dependencies are included. If you are using Maven, include the following dependencies in your pom.xml:

        <!-- ... -->


Spring XML Configuration

After adding the required dependencies and repository declarations, we can create our Spring configuration. The Spring configuration is responsible for creating a Servlet Filter that replaces the HttpSession with an implementation backed by Spring Session and GemFire.

Add the following Spring Configuration:


        <context:property-placeholder location="classpath:META-INF/spring/"/>

        <bean class="sample.GemFireCacheServerReadyBeanPostProcessor"/>

        <util:properties id="gemfireProperties">
                <prop key="log-level">${sample.httpsession.gemfire.log-level:warning}</prop>

        <gfe:client-cache properties-ref="gemfireProperties" pool-name="gemfirePool"/>

        <gfe:pool keep-alive="false"
                <gfe:server host="${}"

        <bean class=""
                  p:maxInactiveIntervalInSeconds="30" p:poolName="DEFAULT"/>
1 Spring annotation configuration support is enabled with <context:annotation-config/> element so that any Spring beans declared in the XML config that are annotated with either Spring or Standard Java annotations supported by Spring will be configured appropriately.
2 The META-INF/spring/ file are used along with the PropertySourcesPlaceholderConfigurer bean to replace placeholders in the Spring XML configuration meta-data with the approrpriate property values.
3 Then the `GemFireCacheSeverReadyBeanPostProcessor`is registered to determine whether a GemFire Server at the designated host/port is running and listening for client connections, blocking client startup until the server is available and ready.
4 Next, we include a Properties bean to configure certain aspects of the GemFire client cache using GemFire’s System Properties. In this case, we are just setting GemFire’s log-level from a application-specific System property, defaulting to warning if unspecified.
5 Then we create a instance of a GemFire ClientCache initialized with our gemfireProperties.
6 We configure a Pool of client connections to talk to the GemFire Server in our Client/Server topology. In our configuration, we use sensible settings for timeouts, number of connections and so on. Also, our Pool has been configured to connect directly to a server.
7 Finally, the GemFireHttpSessionConfiguration is registered to enable Spring Session functionality.
In typical GemFire deployments, where the cluster includes potentially hundreds of GemFire data nodes (servers), it is more common for clients to connect to one or more GemFire Locators running in the cluster. A Locator passes meta-data to clients about the servers available, load and which servers have the client’s data of interest, which is particularly important for single-hop, direct data access. See more details about the Client/Server Topology in GemFire’s User Guide.
For more information on configuring Spring Data GemFire, refer to the reference guide.

Server Configuration

We have only covered one side of the equation. We also need a GemFire Server for our client to talk to and send session state information to the server to manage.

In this sample, we will use the following GemFire Server Java Configuration:


        <context:property-placeholder location="classpath:META-INF/spring/"/>

        <util:properties id="gemfireProperties">
                <prop key="name">GemFireClientServerHttpSessionXmlSample</prop>
                <prop key="mcast-port">0</prop>
                <prop key="log-level">${sample.httpsession.gemfire.log-level:warning}</prop>
                <prop key="jmx-manager">true</prop>
                <prop key="jmx-manager-start">true</prop>

        <gfe:cache properties-ref="gemfireProperties"/>

        <gfe:cache-server auto-startup="true"

        <bean class=""
1 First, we enable Spring annotation config support with the <context:annotation-config> element so that any Spring beans declared in the XML config that are annotated with either Spring or Standard Java annotations supported by Spring will be configured appropriately.
2 A PropertySourcesPlaceholderConfigurer is registered to replace placeholders in our Spring XML configuration meta-data with property values in the META-INF/spring/ file.
3 Next, we configure the GemFire Server using GemFire System Properties very much like our P2P samples. With the mcast-port set to 0 and no locators property specified, our server will be standalone. We also allow a JMX client (e.g. Gfsh) to connect to our server with the use of the GemFire-specific JMX System properties.
4 Then we create an instance of a GemFire peer Cache initialized with our GemFire System Properties.
5 We also setup a GemFire CacheServer instance running on localhost, listening to port 11235, ready to accept our client connection.
6 Finally, we enable the same Spring Session functionality we used on the client by registering an instance of GemFireHttpSessionConfiguration, except that we set the session expiration timeout to 30 seconds. We will explain later what this means.

The GemFire Server configuration gets bootstrapped with the following:

@Configuration (1)
@ImportResource("META-INF/spring/session-server.xml") (2)
public class Application {

        public static void main(final String[] args) {
                new AnnotationConfigApplicationContext(Application.class)
Instead of a simple Java class with a main method, you could also use Spring Boot.
1 The @Configuration annotation designates this Java class as a source for Spring configuration meta-data using Spring’s annotation configuration support.
2 Primarily, the configuration comes from the META-INF/spring/session-server.xml file, which is also the reason why Spring Boot was not used in this sample, since using XML seemingly defeats the purpose and benefits of using Spring Boot. However, this sample is about demonstrating how to use Spring XML to configure the GemFire client and server.

XML Servlet Container Initialization

Our Spring XML Configuration created a Spring bean named springSessionRepositoryFilter that implements Filter. The springSessionRepositoryFilter bean is responsible for replacing the HttpSession with a custom implementation that is backed by Spring Session and GemFire.

In order for our Filter to do its magic, we need to instruct Spring to load our session-client.xml configuration file. We do this with the following configuration:


The ContextLoaderListener reads the contextConfigLocation context parameter value and picks up our session-client.xml configuration file.

Finally, we need to ensure that our Servlet Container (i.e. Tomcat) uses our springSessionRepositoryFilter for every request.

The following snippet performs this last step for us:


The DelegatingFilterProxy will look up a bean by the name of springSessionRepositoryFilter and cast it to a Filter. For every request that DelegatingFilterProxy is invoked, the springSessionRepositoryFilter will be invoked.

HttpSession with GemFire (Client/Server) using XML Sample Application

Running the httpsession-gemfire-clientserver-xml Sample Application

You can run the sample by obtaining the source code and invoking the following commands.

First, you need to run the server using:

$ ./gradlew :samples:httpsession-gemfire-clientserver-xml:run [-Dsample.httpsession.gemfire.log-level=info]

Now, in a separate terminal, you can run the client using:

$ ./gradlew :samples:httpsession-gemfire-clientserver-xml:tomcatRun [-Dsample.httpsession.gemfire.log-level=info]

You should now be able to access the application at http://localhost:8080/. In this sample, the web application is the client cache and the server is standalone.

Exploring the httpsession-gemfire-clientserver-xml Sample Application

Try using the application. Fill out the form with the following information:

  • Attribute Name: username

  • Attribute Value: john

Now click the Set Attribute button. You should now see the values displayed in the table.

How does it work?

We interact with the standard HttpSession in the SessionServlet shown below:

public class SessionServlet extends HttpServlet {

        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                String attributeName = request.getParameter("attributeName");
                String attributeValue = request.getParameter("attributeValue");
                request.getSession().setAttribute(attributeName, attributeValue);
                response.sendRedirect(request.getContextPath() + "/");

        private static final long serialVersionUID = 2878267318695777395L;

Instead of using Tomcat’s HttpSession, we are actually persisting the values in GemFire. Spring Session creates a cookie named SESSION in your browser that contains the id of your session. Go ahead and view the cookies (click for help with Chrome or Firefox).

The following instructions assume you have a local GemFire installation. For more information on installation, see Installing Pivotal GemFire.

If you like, you can easily remove the session using gfsh. For example, on a Linux-based system type the following at the command-line:

$ gfsh

Then, enter the following commands in Gfsh ensuring to replace 70002719-3c54-4c20-82c3-e7faa6b718f3 with the value of your SESSION cookie, or the session ID returned by the GemFire OQL query (which should match):

gfsh>connect --jmx-manager=localhost[1099]

gfsh>query --query='SELECT * FROM /ClusteredSpringSessions.keySet'

Result     : true
startCount : 0
endCount   : 20
Rows       : 1



gfsh>remove --region=/ClusteredSpringSessions --key="70002719-3c54-4c20-82c3-e7faa6b718f3"
The GemFire User Guide has more detailed instructions on using gfsh.

Now visit the application at http://localhost:8080/ again and observe that the attribute we added is no longer displayed.

Alternatively, you can wait 30 seconds for the session to timeout (i.e. expire) and refresh the page. Again, the attribute we added should no longer be displayed in the table. However, keep in mind, that by refreshing the page, you will inadvertently create a new (empty) session. If you run the query again, you will also see two session IDs, the new and the old, since GemFire keeps a "tombstone" of the old session around.