【问题标题】:Path attribute in Spring [closed]Spring中的路径属性[关闭]
【发布时间】:2013-07-15 05:01:06
【问题描述】:

谁能解释一下 path 属性如何在 Spring 中将对象从 html 表单绑定到 Java 类。我是 Spring Web 框架的新手,请帮忙。

【问题讨论】:

  • 尝试搜索“spring form tags”。它看起来像带有 spring 属性的 html 标签,用于将 html 表单绑定到对象。
  • 我这样做了,但没有有用的信息,无法理解,所以尝试询问 Stack :)

标签: java spring class


【解决方案1】:

长话短说,path 属性使用 java beans 约定绑定到 java 属性中。例如以下形式:

<form:form method="post" modelAttribute="theStudent">
  Name: <form:input type="text" path="name"/>
  Cool?: <form:input type"checkbox" path="cool"/>
  <button>Save</button>
</form:form>

以及以下控制器处理方法:

@RequestMapping(...)
public String updateStudent(@ModelAttribute("theStudent") Student student) {
  // ...
}

如果 Student 类使用以下属性定义,将自动绑定:

public class Student {
  private String name;
  public String getName() { return this.name; }
  public void setName(String name) { this.name = name; }

  private boolean cool;
  public boolean isCool() { return this.cool; }
  public void setCool(boolean cool) { this.cool = cool; }
}

有关 JavaBeans 大会的更多信息,请访问section 8.3 of the specification document

【讨论】:

  • 命令对象呢?
  • 这只是modelAttribute的另一种语法。所以commandObject="theStudent" 会给出同样的结果
  • 您好,除非您在表单中添加 commandName="command",否则这将不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
相关资源
最近更新 更多