gpt4 book ai didi

java - spring mvc 表单 :select tag

转载 作者:IT老高 更新时间:2023-10-28 13:44:06 26 4
gpt4 key购买 nike

我有一个包含国家列表(列表)的模型和一个包含国家对象的用户对象。我认为用户可以选择他的国家。
这是我的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]

知道如何克服这个问题吗?

最佳答案

您需要以某种方式告诉 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);
}

...

}

关于java - spring mvc 表单 :select tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12875299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com