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

查看:96
本文介绍了如何使用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).

发布的代码的一个注释是 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天全站免登陆