java 如何使用 Spring MVC 将会话属性作为方法参数(参数)传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3621266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:41:40  来源:igfitidea点击:

How to pass a session attribute as method argument (parameter) with Spring MVC

javaspringspring-mvc

提问by Bozho

In short, I want something like:

简而言之,我想要这样的东西:

public String action(@SessionAttribute User user) {..}

instead of

代替

public String action(HttpSession session) {
     User user = session.getAttribute("user");
}

Mainly for the sake of:

主要是为了:

  • readability
  • unit testing
  • 可读性
  • 单元测试

回答by Bozho

I found a solution.

我找到了解决方案

The idea is to register a custom WebArgumentResolverfor the AnnotationMethodHandlerAdapter, which handles a custom annotation - @SessionAttribute(or @SessionParam).

我们的想法是注册自定义WebArgumentResolverAnnotationMethodHandlerAdapter,它可以处理一个自定义的注释- @SessionAttribute(或@SessionParam)。

One note to the code posted there is that param.getParameterName()can be used if no valueis specified.

对发布在那里的代码的一个说明是,param.getParameterName()如果value指定了no ,则可以使用该代码。

回答by drew

For those arriving via Google, as of at least 4.3.2.RELEASE, Spring includes a @SessionAttributeannotation built-in:

对于那些通过谷歌到达的人,至少从 4.3.2.RELEASE 开始,Spring 包含一个@SessionAttribute内置的注释:

public String action(
    @SessionAttribute(required=false, name="user") User user) {

    // ...

}

A custom solution is no longer necessary.

不再需要自定义解决方案。

回答by Shrirang Edgaonkar

Even if we use @ModelAttribute("user") User user as the method parameter and then use user object in your method it will have updated user from session. The attribute name has to match with the session attribute name "user".

即使我们使用 @ModelAttribute("user") User user 作为方法参数,然后在您的方法中使用 user 对象,它也会从会话中更新用户。属性名称必须与会话属性名称“user”匹配。

public String myMethod( @ModelAttribute("user") User user ){

 System.out.println(user.getDetails());

}