Spring Форма mvc: выберите тег
У меня есть модель, которая содержит список стран (список) и объект пользователя, который содержит объект Country. У меня есть мнение, что пользователь может выбрать свою страну.
Это фрагмент моей страницы 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>
Это моя модель учетной записи:
public class Account {
private User user;
private List<Country> countries;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
Когда jsp загружает (GET) форму: select отображает выбранный элемент текущей страны пользователя. Проблема в том, что когда я отправляю форму, я получаю это исключение:
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]
Любая идея, как я могу это преодолеть?
Ответы
Ответ 1
Вам нужно как-то сказать Spring преобразовать String
в Country
. Вот пример:
@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);
}
...
}