【问题标题】:HttpContext.Current.Session equivalent in Spring MVCSpring MVC 中的 HttpContext.Current.Session 等价物
【发布时间】:2014-11-18 04:44:06
【问题描述】:

我是一名 asp.net 开发人员,我现在正在开发一个 Spring MVC 网络项目。

我想编写一个帮助类,让我可以获取当前用户或检查用户是否已登录,诸如此类。

在 asp.net 中,我可以在项目的任何位置创建一个类,并访问当前会话以获取我可以写 HttpContext.Current.Session["CurrentUser"] 的请求。

在 Spring MVC 中有什么方法可以做到这一点?

我找到了这篇博文,说这是不可能的 (here)。但我也发现了这个 stackoverflow 帖子,其中获取当前会话的方法看起来非常类似于 asp.net 方式(here)。但它对我不起作用。

【问题讨论】:

  • 你也使用 Spring Security 吗?
  • 不,我不知道。看起来很有趣。但是我需要这个 Session 来做更多的事情,而不仅仅是身份验证。

标签: jsp spring-mvc httpsession


【解决方案1】:

在 Spring MVC/Spring Security 中,您可以使用 AuthenticationPrincipal 注释将给定参数解析为当前经过身份验证的用户。

@RequestMapping("/user")
public String show(@AuthenticationPrincipal CustomUser customUser) {
    // do something with CustomUser
    return "view";
}

在后台,当前身份验证是从 SecurityContext 中获取的:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

您可以使用SecurityContextHolder 在代码中的任何位置检索当前身份验证。但为了保持高清晰度和可测试性,请将其保持在最低限度。

如果您想从/向当前 http 会话检索或写入数据,只需指示 Spring MVC 将其提供给您:

@RequestMapping("/user")
public String show(HttpSession session) {
    // do something with session data
    session.getAttribute("myAttr");
    return "view";
}

如果您想在会话中保存多个请求的数据,例如向导,您可以利用 Spring 所谓的SessionAttributes

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2014-02-12
    • 2019-04-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多