Spring MVC形式:选择标签 [英] spring mvc form:select tag

查看:78
本文介绍了Spring MVC形式:选择标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存国家(地区)列表(列表)的模型和一个保存国家(地区)对象的用户对象.我认为用户可以选择他的国家.
这是我的jsp页面的片段:

I have a Model that holds a list of Countries (List) and a user object that holds a Country object. I have a view that the user can select his country.
This is snippet of my jsp page:

<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将显示当前用户所在国家/地区的选定项目.问题是,当我发布表格时,会出现以下异常:

When the jsp loads (GET) the form:select displays the selected item of the current user country. 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?

推荐答案

您需要以某种方式告诉Spring将String转换为Country.这是一个示例:

You need to somehow tell Spring to convert a String to a 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);
    }

}

...
public class MyController {

    private @Autowired CountryEditor countryEditor;

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

    ...

}

这篇关于Spring MVC形式:选择标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆