首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ModelAttribute中未调用PropertyEditor

ModelAttribute中未调用PropertyEditor
EN

Stack Overflow用户
提问于 2013-07-23 02:00:15
回答 1查看 417关注 0票数 1

正如我的标题,我有问题,我不明白为什么它不能。所以,我有一个Person类,PersonPropertyEditor类和控制器。

这就是它:

Person类:

代码语言:javascript
复制
public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

PersonPropertyEditor类:

代码语言:javascript
复制
public class PersonPropertyEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Person person = new Person();
        person.setName(text);

        setValue(person);
    }
}

控制器:

代码语言:javascript
复制
    @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文件:

代码语言:javascript
复制
    <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吗?

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2017-02-20 16:42:33

我使用@JsonDeserialize解决了这个问题

代码语言:javascript
复制
@JsonDeserialize(using=DateTimeDeserializer.class)
public DateTime getPublishedUntil() {
    return publishedUntil;
}

我必须实现自定义的反序列化程序。

代码语言:javascript
复制
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;
        }
}

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17794255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档