如何使用 Spring MVC 将会话属性作为方法参数(参数)传递 [英] How to pass a session attribute as method argument (parameter) with Spring MVC

查看:28
本文介绍了如何使用 Spring MVC 将会话属性作为方法参数(参数)传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In short, I want something like:

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

代替

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

主要是为了:

  • 可读性
  • 单元测试

推荐答案

我发现了一个 解决方案.

想法是注册一个自定义的WebArgumentResolver 用于 AnnotationMethodHandlerAdapter,它处理自定义注释 - @SessionAttribute(或 @SessionParam).

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

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

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

这篇关于如何使用 Spring MVC 将会话属性作为方法参数(参数)传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆