12

国のリスト (リスト) を保持するモデルと、国オブジェクトを保持するユーザー オブジェクトがあります。ユーザーが自分の国を選択できるという見解があります。
これは私の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) されると、form: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]

どうすればこれを克服できますか?

4

1 に答える 1

7

Stringaを aに変換するように Spring に何らかの方法で指示する必要があります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);
    }

    ...

}
于 2012-10-13T19:01:19.187 に答える