在 Spring MVC 中,我想要一个带有 html 下拉列表的表单,该表单由域对象列表支持,但仅显示对象中的一个字段。提交表单后,我希望能够检索整个对象。我可以这样做吗?
最佳答案
如果我理解正确的话,这显然是可能的......
型号
public class Foo() {
private String result;
public String getResult() { return result; }
public void setResult(String result) { this.result = result; }
}
Controller
这是使用注释。如果您不明白这是做什么的,您可能应该查看 Spring 文档。 @ModelAttribute("fooResults")
将可供您的 View 用于下拉元素。 @ModelAttribute("command") Foo foo
会自动“吸收”您在下拉列表中选择的任何内容。
@Controller
public class FooController() {
@ModelAttribute("fooResults")
public List<String> fooResults() {
// return a list of string
}
@RequestMapping(method = RequestMethod.GET)
public String get(@ModelAttribute("command") Foo foo) {
return "fooView";
}
@RequestMapping(method = RequestMethod.POST)
public String post(@ModelAttribute("command") Foo foo) {
// do something with foo
}
查看
利用表单标签库的魔力,您可以将下拉列表(form:select
)绑定(bind)到模型的 result 属性,并使用 fooResults< 填充项目
.
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form commandName="command">
<form:select path="result">
<form:options items="${fooResults}" itemLabel="result" itemValue="result"/>
</form:select>
<input type="submit" value="submit"/>
</form>
这一切都假设您知道自己在做什么:) 如果您不知道,请查看 http://static.springsource.org/docs/Spring-MVC-step-by-step/
关于java - 在 Spring MVC 中,我可以有一个带有支持对象的有状态下拉列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147921/