In Spring MVC, I want to have a form with an html drop down which is backed by a list of domain objects, but only displays one field from the objects. When the form is submitted, I want to be able to retrieve the entire object. Can I do this?
A:
It's obviously possible, if I have understood you correctly...
Model
public class Foo() {
private String result;
public String getResult() { return result; }
public void setResult(String result) { this.result = result; }
}
Controller
This is using annotations. If you don't understand what this is doing you should probably check out the Spring documentation. The @ModelAttribute("fooResults")
will be available to your view to use for your drop down elements. The @ModelAttribute("command") Foo foo
will automatically "suck up" whatever you selected in the drop down.
@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
}
View
Using the magic of the form tag library, you can bind a drop down (the form:select
) to the result property of the model, and populate the items with the 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>
This all assumes you kind of know what you're doing :) If you don't, check out http://static.springsource.org/docs/Spring-MVC-step-by-step/
Ben J
2010-06-30 10:37:45