假设我想将HTTP参数数据绑定到的实例
class Continent {
Integer id
String name
Country country
}
其中Country
类看起来像:
class Country {
Integer id
String name
Currency currency
// other properties
}
如果我想将Continent.country
绑定到已经存在并且可以使用检索的Country
实例
interface CountryService {
Country get(Integer countryId)
}
一个简单的方法是定义一个PropertyEditor
,它可以将国家的ID转换为相应的Country
实例,例如
public class ProductTypeEditor extends PropertyEditorSupport {
CountryService countryService // set this via dependency injection
void setAsText(String paramValue) {
if (paramValue)
value = countryService.get(paramValue.toInteger())
}
public String getAsText() {
value?.id.toString()
}
}
如果我想数据绑定的实例
class Continent {
Integer id
String name
Collection<Country> countries
}
并且在HTTP(数组参数(中发送国家的ID。有没有简单的方法来绑定Collection<Country>
,例如通过定义另一个PropertyEditor
?
属性编辑器只是字符串<->的包装器对象您将不得不自己对数据进行封送处理和取消封送处理。就像你为Country所做的一样。
我会创建一个做的服务
Collection<Country> getCountries(int[] id)
然后使用PropertyEditor拆分并使用您的服务。我认为你不会找到更好的解决方案。你可以做一些类似的事情
void setAsText(String paramValue) {
ids = param.split(",")
// make each id an int
value = service.getCountries(ids)
}