正如我的标题,我有问题,我不明白为什么它不能。所以,我有一个Person类,PersonPropertyEditor类和控制器。
这就是它:
Person类:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}PersonPropertyEditor类:
public class PersonPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
Person person = new Person();
person.setName(text);
setValue(person);
}
}控制器:
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.registerCustomEditor(Person.class,
new PersonPropertyEditor());
}
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String homePost(
@ModelAttribute("personConverted") Person personConverted) {
System.out.println(personConverted.getName());
return "redirect:/home";
}JSP文件:
<form action="addPerson" method="post">
<input type="text" name="personConverted" />
<input type="submit" value="Submit" />
<form>所以,我注册了一个自定义属性编辑器,在控制器中,我将从string转换为person对象,但是我不知道为什么当我使用ModelAttribute时,Spring不会调用我的自定义属性编辑器,但是如果我使用RequestParam,就可以了。
我知道我可以使用Converter来做这件事,但我只是想知道为什么Spring不调用它,这是Spring的bug吗?
提前感谢!
发布于 2017-02-20 16:42:33
我使用@JsonDeserialize解决了这个问题
@JsonDeserialize(using=DateTimeDeserializer.class)
public DateTime getPublishedUntil() {
return publishedUntil;
}我必须实现自定义的反序列化程序。
public class DateTimeDeserializer extends StdDeserializer<DateTime> {
private DateTimeFormatter formatter = DateTimeFormat.forPattern(Constants.DATE_TIME_FORMAT);
public DateTimeDeserializer(){
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser json, DeserializationContext context) throws IOException, JsonProcessingException {
try {
if(StringUtils.isBlank(json.getText())){
return null;
}
return formatter.parseDateTime(json.getText());
} catch (ParseException e) {
return null;
}
}}
https://stackoverflow.com/questions/17794255
复制相似问题