Java SpringMVC表单:选择标签
我有一个保存国家列表(list)的模型和一个保存国家对象的用户对象。我认为用户可以选择他的国家。Java SpringMVC表单:选择标签,java,forms,spring,spring-mvc,types,Java,Forms,Spring,Spring Mvc,Types,我有一个保存国家列表(list)的模型和一个保存国家对象的用户对象。我认为用户可以选择他的国家。 这是我的jsp页面的片段: <form:select path="user.country"> <form:option value="-1">Select your country</form:option> <form:options items="${account.countries}" itemLabel="name" itemV
这是我的jsp页面的片段:
<form:select path="user.country">
<form:option value="-1">Select your country</form:option>
<form:options items="${account.countries}" itemLabel="name" itemValue="id" />
</form:select>
你知道我如何克服这个问题吗?你需要告诉Spring把
字符串
转换成国家的。以下是一个例子:
@Component
public class CountryEditor extends PropertyEditorSupport {
private @Autowired CountryService countryService;
// Converts a String to a Country (when submitting form)
@Override
public void setAsText(String text) {
Country c = this.countryService.findById(Long.valueOf(text));
this.setValue(c);
}
}
及
谢谢-这就成功了。有一件事我还不明白。如果在发布数据时需要自定义转换器,为什么在获取数据时不需要?(加载页面时,所选国家/地区与用户拥有的国家/地区对象相同)@MrT。Spring MVC巧妙地处理select
表单。您的表单:选择具有path=“user.country”
。因此,如果用户已经拥有id为42的国家/地区,则值为42的选项标记将具有selected=“selected”
属性。要了解更多信息,.someas!他工作得很完美,我想更多地了解它是如何工作的。
Field error in object 'account' on field 'user.country': rejected value [90];
codes [typeMismatch.account.user.country,typeMismatch.user.country,typeMismatch.country,typeMismatch.org.MyCompany.entities.Country,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [account.user.country,user.country];
arguments []; default message [user.country]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'org.MyCompany.entities.Country' for property 'user.country';
nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.MyCompany.entities.Country] for property 'country': no matching editors or conversion strategy found]
@Component
public class CountryEditor extends PropertyEditorSupport {
private @Autowired CountryService countryService;
// Converts a String to a Country (when submitting form)
@Override
public void setAsText(String text) {
Country c = this.countryService.findById(Long.valueOf(text));
this.setValue(c);
}
}
...
public class MyController {
private @Autowired CountryEditor countryEditor;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Country.class, this.countryEditor);
}
...
}