Spring中有哪几种方法获取HttpSession对象

Spring MVC

可以直接作为Controller的参数传入:

  1. @RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  2. @ResponseBody
  3. public Map test(HttpSession session, String otherParam) {
  4. //TODO
  5. return null;
  6. }

其它

要获取HttpSession,只需要获取到HttpServletRequest,然后调用HttpServletRequest的getSession方法

1、注解自动注入

  1. @Autowired
  2. private HttpSession session;
  3. @Autowired
  4. private HttpServletRequest request;

2、普通类中获取

  1. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  2. request.getSession();
相关推荐
掘金小豆3 小时前
Spring 事务失效的 6 大场景,你踩过几个?
后端·spring·面试
咖啡八杯2 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
Flittly3 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
咖啡八杯4 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
Flittly5 天前
【AgentScope Java新手村系列】(14)人机交互
java·spring boot·spring
唐青枫6 天前
MySQL JSON 实战详解:从存储、查询、更新到 JSON_TABLE 与索引
sql·mysql
掉头发的王富贵8 天前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
唐青枫9 天前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
咖啡八杯11 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
Flittly12 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring