简体   繁体   English

spring mvc form:选择标签

[英]spring mvc form:select tag

I have a Model that holds a list of Countries (List) and a user object that holds a Country object. 我有一个Model,它包含一个States(List)列表和一个包含Country对象的用户对象。 I have a view that the user can select his country. 我认为用户可以选择他的国家。
This is snippet of my jsp page: 这是我的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>

This is my Account model: 这是我的帐户模型:

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;
    }
}

When the jsp loads (GET) the form:select displays the selected item of the current user country. 当jsp加载(GET)表单时:select显示当前用户所在国家/地区的选定项目。 The problem is that when i post the form i get this exception: 问题是,当我发布表单时,我得到这个例外:

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]

Any idea how i can overcome this? 知道如何克服这个问题吗?

You need to somehow tell Spring to convert a String to a Country . 你需要以某种方式告诉Spring将String转换为Country Here is an example : 这是一个例子:

@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);
    }

}

and

...
public class MyController {

    private @Autowired CountryEditor countryEditor;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Country.class, this.countryEditor);
    }

    ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM