I have the following (simplified) form in one of my views:
<form:form commandName="entry" method="POST">
<form:input type="text" path="name"/>
<form:input type="text" path="tags" />
<input type="submit" value="Submit"/>
</form:form>
What will be associated with the following JavaBean:
public class Entry {
private String name;
private List<Tag> tags = new LinkedList<Tag>();
}
because I want to use all the new fancy features of Spring 3, I use an annotation-driven controller to receive the POST request:
@Controller
@RequestMapping("/entry")
public class EntryController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView show() {
ModelAndView mav = new ModelAndView("entry");
mav.addObject(new Entry());
return mav;
}
@RequestMapping(method = RequestMethod.POST)
public String add(@ModelAttribute("entry") @Valid Entry entry,
BindingResult result) {
}
}
As you can see, I need to convert the input text (which looks like tag1, tag2, tag3) to a list of tags, define it like this:
public class Tag {
private String name;
}
There are several ways to do this with Spring 3.0:
( Sorry, long post, questions are in bold )
Simplest
Programming a new property tagsAsTextto have getter / setter as a String:
public class Entry {
public void setTagsAsText(String tags) {
}
public String getTagsAsText() {
}
}
This approach has two drawbacks:
BeanInfo
BeanInfo bean:
public class EntryBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
@Override
PropertyDescriptor tagsDescriptor = new PropertyDescriptor("tags", Entry.class) {
@Override
public PropertyEditor createPropertyEditor(Object bean) {
return new EntryTagListEditor(Integer.class, true);
};
};
return new PropertyDescriptor[] { tagListDescriptor };
}
catch (IntrospectionException ex) {
throw new Error(ex.toString());
}
}
}
public class EntryTagListEditor extends PropertyEditorSupport {
public void setAsText(String text) {
}
public String getAsText() {
}
}
:
- BeanInfo , / Entry. BeanInfo (, " , , " )
BindingResult ?
Java 5:
final class StringToTagList implements Converter<String, List<Tag>> {
public List<Tag> convert(String source) {
}
}
, :
- , ,
ConversionServiceFactoryBean, ? - ()
BindingResult ?