java – 方法参数级别的@ModelAttribute注释是什么意思?

前端之家收集整理的这篇文章主要介绍了java – 方法参数级别的@ModelAttribute注释是什么意思?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@

Spring 3参考资料告诉我们:

When you place it on a method
parameter,@modelattribute maps a
model attribute to the specific,
annotated method parameter

我不明白这个魔法咒语,因为我确定模型对象的别名(如果使用ModelMap作为返回类型的键值)在执行请求处理程序方法后传递给View.因此,当请求处理程序方法执行时,模型对象的名称无法映射到方法参数.

为了解决这个矛盾我去了stackoverflow并找到了this详细的例子.
例子的作者说:

// The “personAttribute” model has
been passed to the controller from the
JSP

看来,他被Spring引用所吸引……

为了消除魅力,我在我的环境中部署了他的示例应用程序,并从方法MainController.saveEdit()中残留地剪切了@modelattribute注释.结果应用程序无需任何更改即可运行!所以我的结论是:将Web表单的字段值传递给参数的字段不需要@modelattribute注释.然后我坚持这个问题:@modelattribute注释的意思是什么?如果唯一的意思是在View中为模型对象设置别名,那么为什么这种方式比将对象显式添加到ModelMap更好呢?

最佳答案
关键是@modelattribute是可选的 – 如果参数没有注释且它的类型没有特殊含义(即它不是HttpServletRequest,ModelMap等),它被视为@ ModelAttribute-annotated参数.

因此,在两种情况下有效地需要@modelattribute

>指定属性名称.如果省略@modelattribute或具有空值,则使用默认名称(带有第一个字母decapitalized的参数的类型名称).
>如果参数的类型具有特殊含义.例如,如果您的域对象作为属性传递扩展java.security.Principal,则需要对其进行注释,否则Spring将传递HttpServletRequest.getUserPrincipal()的结果.

有些人倾向于在没有实际需要的情况下使用@modelattribute来记录参数的含义.

原文链接:https://www.f2er.com/spring/432565.html

猜你在找的Spring相关文章