【问题标题】:Does a variable with @ModelAttribute get populated from request parameters?带有 @ModelAttribute 的变量是否从请求参数中填充?
【发布时间】:2018-08-23 16:59:19
【问题描述】:

我对 Spring @ModelAttribute 在方法参数方面的工作细节感兴趣。

正如我们所知,当模型中缺少请求的属性时,它的实例会被创建并从视图表单中填充。

我的问题涉及表单没有预期属性但这些属性在 URL 模板参数中可用的情况。 我想知道在这种情况下,我们的变量是否会填充这些请求参数的值?

例如,像这里一样,变量 attributeToPopulate 是否会使用来自 URL http://localhost:8080/MyApp/parameter1=whatever?parameter2=whatever?parameter3=whatever 的参数 1、2、3 填充?:

RequestMapping(method = RequestMethod.GET)
public  String fooMethod(@ModelAttribute("attributeName") FooClass attributeToPopulate){
// method implementation
return "view";
}

Spring 文档、参考文档和问答网站均未明确提及此类情况。但是,Stack Overflow 上的one post 确实提到了用 ModelAtrribute 注释的变量以这种方式填充(用户 Xelian 的回答):

name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&

考虑到少数人对该答案的支持,我有点怀疑,但同时对@ModelAttribute 是否确实以这种方式起作用感到好奇。

任何信息性输入将不胜感激。

【问题讨论】:

  • 请接受我的回答。或者您还有什么问题?
  • 在其初始(未经编辑)版本中,您的回答并未涉及我的问题。这也是我一开始不接受的原因

标签: spring spring-mvc modelattribute


【解决方案1】:

您可以在FooClass 中为字段设置默认值,而不是在RequestMapping 注释中设置它们。在这种情况下,您不必在使用FooClass 的所有方法中将RequestMapping 与默认值复制粘贴为ModelAttribute。 @tomatefraiche 我试图通过

做到这一点
<spring:url value="/hello?name=default" var="userActionUrl" />
<form:form method="get" modelAttribute="user" action="${userActionUrl}">
  <form:input path="name" type="text" disabled="true" />
</form:form>

@GetMapping("/hello")   
  public String hello(@ModelAttribute("user") User user, Model model) {
  model.addAttribute("name", user.name);
  model.addAttribute("user", user);
  return "hello";

}

并且看起来像 Spring 覆盖 url 中的值。在控制器中有一个空值。提交表单后,URL 也是hello?name=。所以看起来你不能通过 url 设置默认值,因为它将被替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多