弹簧。如何使用PropertyEditors转换对象属性?

时间:2014-12-21 17:34:50

标签: java spring propertyeditor

我有弹簧窗体的jsp页面:

<form:form id="edit-form" method="POST" commandName="item"
                    action="items">
    <form:input id="title" path="title" type="text" />

    <form:textarea id="description" path="description"></form:textarea>

    <form:input id="timeLeft" type="text" path="timeLeft" />

    <button type="submit" id="sell-item">Create/Edit</button>

</form:form>

在clienside timeleft格式:HH:MM,但在服务器端我们需要将其转换为毫秒(长)。怎么做(从客户端来对象(标题,描述,时间段))?如何转换自定义对象中的特定属性?

我正在尝试做类似的事情:

使用initBinder方法的Controller类:

@InitBinder
private void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, "item.timeLeft",
            new TimeleftPropertyEditor());
}

@RequestMapping(method = RequestMethod.POST)
public void create(@ModelAttribute("item") Item item, BindingResult result) {
    System.out.println(item + ": " +result.getAllErrors());
}

TimeleftPropertyEditor:

public class TimeleftPropertyEditor extends PropertyEditorSupport {
private static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
private static final int MILLIS_IN_MINUTE = 60 * 1000;

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Long result = null;
        if (text != null) {
            String[] time = text.split(":");
            if (time.length != 1) {
                long hours = Long.parseLong(time[0]) * MILLIS_IN_HOUR;
                long minutes = Long.parseLong(time[1]) * MILLIS_IN_MINUTE;
                result = hours + minutes;
            } else {
                result = -1L;
            }
        }
        setValue(result);
    } 
}

但是当请求提交时setAsText方法没有调用。 BindingResult对象有错误: [字段'timeLeft'中对象'item'中的字段错误:被拒绝的值[12:33];代码[typeMismatch.item.timeLeft,typeMismatch.timeLeft,typeMismatch.java.lang.Long,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [item.timeLeft,timeLeft];参数[];默认消息[timeLeft]]; default message [无法将'java.lang.String'类型的属性值转换为属性'timeLeft'所需的类型'java.lang.Long';嵌套异常是java.lang.NumberFormatException:对于输入字符串:“12:33”]]

0 个答案:

没有答案