1. Overview

Spring boot provides easy ways for rest service development, Spring boot also provide ways to manage session in restful web services. When a session needs to maintain using restful web service then session token need to pass using header because cookies cannot be maintained in restful services. When session will be created it will return response header x-auth-token on the first request and while every next request x-auth-token header contains so the session will be maintained.

Spring boot rest service session requires Redis store, We are assuming that Redis service is running on 6379 port:

Spring Boot Rest Service Session Example - Redis Server

Spring Boot Rest Service Session Example – Redis Server

2. Example

Spring Boot Rest Service Session Example

Spring Boot Rest Service Session Example

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>spring-boot-example</groupId>
    <artifactId>Spring-boot-session-example-using-redis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <description>Spring boot rest service session example, It will store session id in browser.</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- Provided -->
        <dependency>
            <groupId>org.springframework.boot</groupId>                <!-- for tomcat web container-->
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>         <!-- spring boot session dependency -->
            <artifactId>spring-session</artifactId> 
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>            <!-- spring redis store dependency -->
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.3.1.RELEASE</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>biz.paluch.redis</groupId>
            <artifactId>lettuce</artifactId>
            <version>3.5.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>         <!--its for spring mvc related -->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 SpringBootConfig

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@SpringBootApplication
@ComponentScan
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootConfig.class);
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
}

2.3 HttpSessionConfig

HttpSessionStrategy bean indicate that session will be maintained using header x-auth-token.

package com.javadeveloperzone;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;

/**
 * Created by Java Developer Zone on 13-11-2017.
 */
@Configuration
@EnableRedisHttpSession
public class HttpSessionConfig extends AbstractHttpSessionApplicationInitializer {
    @Bean
    public JedisConnectionFactory connectionFactory() {     // It will create filter for Redis store which will override default Tomcat Session
        return new JedisConnectionFactory();
    }
    @Bean
    public HttpSessionStrategy httpSessionStrategy() {      // Header Strategy indicate that session will be manage using header 
        return new HeaderHttpSessionStrategy();
    }
}

2.4 SpringBooRedisStoreController

This controller will create a session (If not exists) and store user visit, increment visit on each request.

package com.javadeveloperzone.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
/**
 * Created by Lenovo on 19-07-2017.
 */
@RestController
public class SpringBooRedisStoreController {
    @GetMapping("/viewSessionData")                     // it will handle all request for /welcome
    public java.util.Map<String,Integer> start(HttpServletRequest request) {
        Integer integer =(Integer) request.getSession().getAttribute("hitCounter");
        if(integer==null){
            integer=new Integer(0);
            integer++;
            request.getSession().setAttribute("hitCounter",integer);
        }else{
            integer++;
            request.getSession().setAttribute("hitCounter",integer);
        }
        java.util.Map<String,Integer> hitCounter=new HashMap<>();
        hitCounter.put("Hit Counter",integer);
        return hitCounter;
    }
}

Demo:

Step 1: Session Created and Return Header Token

The session is created so Hit Counter is 1 and also response contains session token which needs to pass in the second request while reusing the same session.

 

Spring Boot Rest Service Session Example - Session Created

Spring Boot Rest Service Session Example – Session Created

Response header token x-auth-token which will be used to second request to reuse the same session.

Spring Boot Rest Service Session Example - Response Token

Spring Boot Rest Service Session Example – Response Token

Step 2: Pass token in header request

Spring Boot Rest Service Session Example - Pass Header

Spring Boot Rest Service Session Example – Pass Header

 

3. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *