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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
This post explains exactly what you want to do: https://www.credera.com/blog/technology-insights/java/spring-mvc-custom-property-editors/. I spend a long time looking for the exact same question, and AJ Angus on Credera has the best explanation I saw on the web.
To summarize, you must tell Spring how to convert the string-form option values on the select tag back into an object. This is done by putting the item values as IDs of the object: So spring now has the ID of the employee, but how does Spring change an ID back into an employee when the user clicks submit? This is by means of a PropertyEditor, which the Spring documentation doesn't explain well:
Then you use initBinder to let the controller know that the propertyEditor exists:
Then you are all set! Check out the link for a better and more detailed explanation.
It's obviously possible, if I have understood you correctly...
Model
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.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 thefooResults
.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/