How to get session information in Spring MVC 3

本文介绍了如何在Spring MVC框架中获取HTTP Session信息,包括Session的创建时间和ID等。通过直接将HttpSession作为控制器方法参数,或者使用RequestContextHolder来获取当前请求的Session,这两种方式可以方便地在控制器中使用Session数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am new to spring MVC and I am trying to get the session information in my controller class

Right now I am using

    HttpSession objHttpSession = request.getSession(true);

if I want to get session creation time and session Id I am using

    objHttpSession.getCreationTime(); objHttpSession.getId();

I want to know is there any spring MVC specific way to get the session details?

I usually declare a parameter of type HttpSession in my Spring MVC controller method when I need to access session details.

For example:

@RequestMapping("/myrequest")
public void handleMyRequest(HttpSession session, ...) {
   ...
}

I think it’s the simplest way, but don’t know if it fits your needs.

You can get the session in Spring MVC like this:

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();

The currentRequestAttributes method return the RequestAttributes currently bound to the thread in which there is a current request and from that request you can get the session. This is useful when you need to get hold of the session in non-spring class. Otherwise you can just use:

@RequestMapping(...)
public void myMethod(HttpSession session) {   
}

Spring will inject HttpSession instance into your controller’s method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值