我有一个带有textarea输入inputTextA
和inputTexB
的Spring表单
我需要将这些输入绑定到以下Model
对象:
public class Model{
private List<String> listA;
private List<CustomObject> listB;
// getters and setters
}
我读到如果我实现Converter接口并在Spring配置类上注册实现,Spring就能自动进行转换。所以我希望Spring能够做到以下几点:
inputA = "12345|67890"
已转换为model.listA = {"12345","12345"}
inputB = "abcd|efgh"
已转换为model.listB = {new CustomObject("abcd"),new CustomObject("efgh")}
但我得到以下内容:
inputA = "12345|67890"
已转换为model.listA = {(new CustomObject("12345")).toString(),(new CustomObject("67890")).toString()}
inputB = "abcd|efgh"
已转换为model.listB = {new CustomObject("abcd"),new CustomObject("efgh")}
我为每个列表实现了Converter Interface,如下所示:
public class StringToStringListConverter implements Converter<String, List<String>>{
@Override
public List<String> convert(String source){
List<String> result = null;
// Conversion logic.
return result;
}
}
,
public class StringToCustomObjectListConverter implements Converter<String, List<CustomObject>>{
@Override
public List<CustomObject> convert(String source){
List<CustomObject> result = null;
// Conversion logic.
return result;
}
}
并在Spring Configuration类上注册每个转换器,覆盖addFormatter方法。
@Override
public void addFormatter(FormatterRegistry registry){
registry.addConverter(new StringToStringListConverter());
registry.addConverter(new StringToCustomObjectListConverter());
}
我有以下观点。
<div class="form-group row">
<label for="inputTextAId" class="col-form-label col-sm-2">
<spring:message code="labelAText"/>
</label>
<div class="col-sm-10">
<form:textarea id="inputTextAId"
class="form-control"
rows="3"
path="model.stringListA">
</form:textarea>
</div>
</div>
<div class="form-group row">
<label for="inputTextBId" class="col-form-label col-sm-2">
<spring:message code="labelBText"/>
</label>
<div class="col-sm-10">
<form:textarea id="structuresId"
class="form-control"
rows="3"
path="model.stringListB">
</form:textarea>
</div>
</div>