【问题标题】:How to inject a value from HttpSession instead of the session如何从 HttpSession 而不是会话注入值
【发布时间】:2019-09-03 16:49:22
【问题描述】:

使用 spring MVC 时,只需将 HttpSession session 添加到方法的签名中,就可以很容易地将 HttpSession 传递给方法,然后您可以执行类似的操作

Integer valueFromSession = (Integer) session.getAttribute("key1")
Integer anotherValueFromSession = (Integer) session.getAttribute("key2")

我现在遇到的问题是,我们需要在许多不同的控制器中以许多不同的方法从会话中获取值,所以我的问题是是否可以从会话中获取值并自动注入它的方法,因此而不是:

@GetMapping("/something")
public String foo(HttpSession session) {
    Integer valueFromSession = (Integer) session.getAttribute("key1")
    Integer anotherValueFromSession = (Integer) session.getAttribute("key2")

    return someMethod(valueFromSession, anotherValueFromSession);
}

我可以:

@GetMapping("/something")
public String foo(HttpSessionData dataFromSession) {

    return someMethod(dataFromSession.getValue(), dataFromSession.getAnotherValue();
}

其中 DataFromSession 是从 HttpSession 填充的类。有没有办法做到这一点?

【问题讨论】:

    标签: java spring spring-mvc httpsession


    【解决方案1】:

    你可以将@SessionAttribute与spring MVC一起使用,它会从会话中检索现有属性,更多见here

    @GetMapping("/something")
    public String foo(@SessionAttribute("key1") Integer key1, @SessionAttribute("key2") Integer key2) {
        return someMethod(key1, key2);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多