有幾種辦法:java
1.擴展指定server程序員
利用Servlet容器提供的插件功能,自定義HttpSession的建立和管理策略,並經過配置的方式替換掉默認的策略。缺點:耦合Tomcat/Jetty等Servlet容器,不能隨意更換容器。web
2.利用Filterredis
利用HttpServletRequestWrapper,實現本身的 getSession()方法,接管建立和管理Session數據的工做。spring-session就是經過這樣的思路實現的。spring
3 利用spring sessionsql
Spring Boot中spring session支持方式:bash
<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;
}
}
複製代碼
源碼面前,了無祕密session
歡迎工做一到五年的Java工程師朋友們加入Java程序員開發: 721575865架構
羣內提供免費的Java架構學習資料(裏面有高可用、高併發、高性能及分佈式、Jvm性能調優、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用本身每一分每一秒的時間來學習提高本身,不要再用"沒有時間「來掩飾本身思想上的懶惰!趁年輕,使勁拼,給將來的本身一個交代!併發