有幾種辦法:java
1.擴展指定server
利用Servlet容器提供的插件功能,自定義HttpSession的建立和管理策略,並經過配置的方式替換掉默認的策略。缺點:耦合Tomcat/Jetty等Servlet容器,不能隨意更換容器。web
2.利用Filter
利用HttpServletRequestWrapper,實現本身的 getSession()方法,接管建立和管理Session數據的工做。spring-session就是經過這樣的思路實現的。redis
3 利用spring sessionspring
Spring Boot中spring session支持方式:session
JDBC、MongoDB、Redis、Hazelcast、HashMapapp
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
server.port=8080 spring.redis.host=localhost spring.redis.port=6379 # spring session使用存儲類型 spring.session.store-type=redis
package com.shyroke; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @EnableCaching @EnableRedisHttpSession @SpringBootApplication public class SpringbootSessionApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSessionApplication.class, args); } }
package com.shyroke.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/") public class IndexController { @ResponseBody @RequestMapping(value = "/session") public Map<String, Object> getSession(HttpServletRequest request) { request.getSession().setAttribute("username", "admin"); Map<String, Object> map = new HashMap<String, Object>(); map.put("sessionId", request.getSession().getId()); return map; } @ResponseBody @RequestMapping(value = "/get") public String get(HttpServletRequest request) { String userName = (String) request.getSession().getAttribute("username"); return userName; } }