Spring boot Rest Service Session Example using JDBC

https://javadeveloperzone.com/spring-boot/spring-boot-rest-service-session-example-using-jdbc/

1. Overview

Spring boot session persist is past of spring boot session management. Sprint boot provides ways to persist session in the database like session id, session creation time, last active time, max inactive interval (session timeout) and session attributes.

Key points of Spring boot Rest Service Session Example using JDBC

  • Make sure that you have added @EnableJdbcHttpSession annotation at to enable JDBC Session
  • Make sure that Database properties are current in application.properties files like spring.datasource.urlspring.datasource.usernamespring.datasource.password,spring.datasource.driver-class-name.
  • If do not want to write database-related properties then create bean @DataSource 
  • Make sure that database drive has been added in classpath or POM
  • HttpSessionStrategy bean requires maintaining session using header (Mostly request for Rest Services)
  • spring-session-jdbc dependency must be available in classpath
  • Copy table schema from org.springframework.session.jdbc.schema-[DATABASE].sql and create table manually. In this example, we have used schema-mysql.sql
  • When any session create it will store session related information database tables by default table names are spring_sessionspring_session_attributes.
  • If do not like spring_session table name then specified a table in the property name spring.session.jdbc.table-name
     like  : spring.session.jdbc.table-name=your_table_spring_session
  • For max_inactive_interval (session timeout) need to specified values in annotation attribute maxInactiveIntervalInSeconds so that values affect in the table.
    1. @EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 1500)
  • Here are some useful other properties:
    1. server.session.timeout= # Session timeout in seconds.
    2. spring.session.jdbc.initializer.enabled= # Create the required session tables on startup if necessary. Enabled automatically if the default table name is set or a custom schema is configured.
    3. spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
    4. spring.session.jdbc.table-name=SPRING_SESSION # Name of database table used to store sessions.

    NOTE : spring.session.jdbc.schema : It is not creating schema automatically. We need to create schema manually. 

2. Example

Spring boot Rest Service Session Example using JDBC

Spring boot Rest Service Session Example using JDBC

2.1 pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>spring-boot-example</groupId>
  7. <artifactId>Spring-boot-session-example-using-jdbc</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10. <description>Spring boot rest service session example using jdbc</description>
  11. <!-- Inherit defaults from Spring Boot -->
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>1.5.4.RELEASE</version>
  16. </parent>
  17. <properties>
  18. <maven.compiler.source>1.8</maven.compiler.source>
  19. <maven.compiler.target>1.8</maven.compiler.target>
  20. </properties>
  21. <dependencies>
  22. <!-- Provided -->
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId> <!-- for tomcat web container-->
  25. <artifactId>spring-boot-starter-tomcat</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.session</groupId> <!-- for spring boot jdbc session -->
  29. <artifactId>spring-session-jdbc</artifactId>
  30. <version>1.3.1.RELEASE</version>
  31. </dependency>
  32. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  33. <dependency>
  34. <groupId>mysql</groupId>
  35. <artifactId>mysql-connector-java</artifactId>
  36. <version>5.1.6</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId> <!--its for spring mvc related -->
  40. <artifactId>spring-boot-starter-web</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-jdbc</artifactId>
  45. </dependency>
  46. </dependencies>
  47. <build>
  48. <plugins>
  49. <plugin>
  50. <groupId>org.springframework.boot</groupId>
  51. <artifactId>spring-boot-maven-plugin</artifactId>
  52. </plugin>
  53. </plugins>
  54. </build>
  55. </project>

2.2 HttpSessionConfig

  1. package com.javadeveloperzone;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession;
  5. import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
  6. import org.springframework.session.web.http.HeaderHttpSessionStrategy;
  7. import org.springframework.session.web.http.HttpSessionStrategy;
  8. /**
  9. * Created by Java Developer Zone on 13-11-2017.
  10. */
  11. @Configuration
  12. @EnableJdbcHttpSession
  13. public class HttpSessionConfig extends AbstractHttpSessionApplicationInitializer {
  14. @Bean
  15. public HttpSessionStrategy httpSessionStrategy() { // maintain session using header (mostly for rest session management)
  16. return new HeaderHttpSessionStrategy();
  17. }
  18. }

2.3 SpringBooJDBCSessionController

  1. package com.javadeveloperzone.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import java.util.HashMap;
  8. /**
  9. * Created by JavaDeveloperZone on 19-07-2017.
  10. */
  11. @RestController
  12. public class SpringBooJDBCSessionController{
  13. @GetMapping("/viewSessionData") // it will handle all request for /welcome
  14. public java.util.Map<String,Integer> start(HttpServletRequest request) {
  15. Integer integer =(Integer) request.getSession().getAttribute("hitCounter"); it will read data from database tables
  16. if(integer==null){
  17. integer=new Integer(0);
  18. integer++;
  19. request.getSession().setAttribute("hitCounter",integer); // it will write data to tables
  20. }else{
  21. integer++;
  22. request.getSession().setAttribute("hitCounter",integer); // it will write data to tables
  23. }
  24. java.util.Map<String,Integer> hitCounter=new HashMap<>();
  25. hitCounter.put("Hit Counter",integer);
  26. return hitCounter;
  27. }
  28. }

2.4 pringBootConfig

  1. package com.javadeveloperzone;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.annotation.ComponentScan;
  5. /**
  6. * Created by JavaDeveloperZone on 19-07-2017.
  7. */
  8. @SpringBootApplication
  9. @ComponentScan
  10. // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
  11. public class SpringBootConfig {
  12. public static void main(String[] args) throws Exception {
  13. SpringApplication.run(SpringBootConfig.class, args); // it wil start application
  14. }
  15. }

2.5 application.properties

  1. spring.datasource.url=jdbc:mysql://localhost/demo_database
  2. spring.datasource.username=root
  3. spring.datasource.password=
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.6 schema-mysql.sql

  1. CREATE TABLE SPRING_SESSION (
  2. SESSION_ID CHAR(36) NOT NULL,
  3. CREATION_TIME BIGINT NOT NULL,
  4. LAST_ACCESS_TIME BIGINT NOT NULL,
  5. MAX_INACTIVE_INTERVAL INT NOT NULL,
  6. PRINCIPAL_NAME VARCHAR(100),
  7. CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (SESSION_ID)
  8. ) ENGINE=InnoDB;
  9. CREATE INDEX SPRING_SESSION_IX1 ON SPRING_SESSION (LAST_ACCESS_TIME);
  10. CREATE TABLE SPRING_SESSION_ATTRIBUTES (
  11. SESSION_ID CHAR(36) NOT NULL,
  12. ATTRIBUTE_NAME VARCHAR(200) NOT NULL,
  13. ATTRIBUTE_BYTES BLOB NOT NULL,
  14. CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_ID, ATTRIBUTE_NAME),
  15. CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_ID) REFERENCES SPRING_SESSION(SESSION_ID) ON DELETE CASCADE
  16. ) ENGINE=InnoDB;
  17. CREATE INDEX SPRING_SESSION_ATTRIBUTES_IX1 ON SPRING_SESSION_ATTRIBUTES (SESSION_ID);

2.7 Run Application

mvn spring-boot:run

  1. [INFO] Scanning for projects...
  2. [INFO]
  3. [INFO] ------------------------------------------------------------------------
  4. [INFO] Building Spring-boot-session-example-using-jdbc 1.0-SNAPSHOT
  5. [INFO] ------------------------------------------------------------------------
  6. [INFO]
  7. [INFO] >>> spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) > test-compile @ Spring-boot-session-example-using-jdbc >>>
  8. [INFO]
  9. [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Spring-boot-session-example-using-jdbc ---
  10. [INFO] Using 'UTF-8' encoding to copy filtered resources.
  11. [INFO] Copying 1 resource
  12. [INFO] Copying 0 resource
  13. [INFO]
  14. [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Spring-boot-session-example-using-jdbc ---
  15. [INFO] Nothing to compile - all classes are up to date
  16. [INFO]
  17. [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Spring-boot-session-example-using-jdbc ---
  18. [INFO] Using 'UTF-8' encoding to copy filtered resources.
  19. [INFO] skip non existing resourceDirectory F:\extrawork\spring-boot\spring-boot-rest-service-session-jdbc-example\src\test\resources
  20. [INFO]
  21. [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Spring-boot-session-example-using-jdb
  22. c ---
  23. [INFO] No sources to compile
  24. [INFO]
  25. [INFO] <<< spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) < test-compile @ Spring-boot-session-example-using-jdbc <<<
  26. [INFO]
  27. [INFO] --- spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) @ Spring-boot-session-example-using-jdbc ---
  28. . ____ _ __ _ _
  29. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  30. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  31. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  32. ' |____| .__|_| |_|_| |_\__, | / / / /
  33. =========|_|==============|___/=/_/_/_/
  34. :: Spring Boot :: (v1.5.4.RELEASE)
  35. 2017-11-25 09:49:51.741 INFO 34908 --- [ main] com.javadeveloperzone.SpringBootConfig : Starting
  36. SpringBootConfig on Mahesh with PID 34908 (F:\extrawork\spring-boot\spring-boot-rest-service-session-jdbc-exam
  37. ple\target\classes started by Lenovo in F:\extrawork\spring-boot\spring-boot-rest-service-session-jdbc-example
  38. )
  39. 2017-11-25 09:49:51.746 INFO 34908 --- [ main] com.javadeveloperzone.SpringBootConfig : No active

2.8 Database:

Table : spring_session

Spring Boot Rest Service Session Example - JDBC

Spring Boot Rest Service Session Example – JDBC

Table : spring_session_attributes

Spring Boot Rest Service Session Example - JDBC - spring-session-attributes

Spring Boot Rest Service Session Example – JDBC – spring-session-attributes

Send First Request, It will create session and store session information in database and return x-auth-token in response header.

Spring Boot Rest Service Session Example - First Request

Spring Boot Rest Service Session Example – First Request

A further request, Pass header  x-auth-token in request so the server will consider the same session.

Spring Boot Rest Service Session Example - Pass Header Information

Spring Boot Rest Service Session Example – Pass Header Information

3. References

转载于:https://www.cnblogs.com/davidwang456/articles/10362284.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值