我们如何在Spring Web Flow中绑定复杂的模型对象? 请看以下示例:
public class User {
int id;
String name;
Address address;
}
public class Address {
int id;
String street;
String city;
}
在视图中,我必须从地址Id更新此用户的地址。该场景是用户搜索不同地址并将一个地址链接到用户的情况。由于搜索结果是地址ID,我们如何将地址Id转换为地址对象?
我目前的观点是 -
<form:form method="POST" modelAttribute="user" action="${flowExecutionUrl}">
<form:inputpath="address.id" />
</form:form>
网络流程如下:
<view-state id="updateAddress" model="flowScope.user">
<binder>
<binding property="address" />
</binder>
<transition on="addressSubmitted" to="addNextInfo"></transition>
<transition on="cancel" to="cancelled" bind="false" />
</view-state>
所以,有两个问题:
答案 0 :(得分:1)
我认为使用自定义转换器是完全正确的。您可能希望扩展现有的StringToObject
转换器。我在这里猜一些类,但转换器可能看起来像这样:
public class StringToAddress extends StringToObject {
private final AddressService addressService;
public StringToAddress(AddressService addressService) {
super(Address.class);
this.addressService = addressService;
}
@Override
protected Object toObject(String string, Class targetClass) throws Exception {
return addressService.findById(string);
}
@Override
protected String toString(Object object) throws Exception {
Address address = (Address) object;
return String.valueOf(address.getId());
}
}
然后您需要配置转换服务:
@Component("conversionService")
public class ApplicationConversionService extends DefaultConversionService {
@Autowired
private AddressService addressService;
@Override
protected void addDefaultConverters() {
super.addDefaultConverters();
// registers a default converter for the Address type
addConverter(new StringToAddress(addressService));
}
}
每当Spring尝试将id绑定到Address字段(并将查找并绑定真实的Address对象)时,它将自动启动。
Keith Donald在他的帖子here中经历了一个示例自定义转换器设置,值得参考。