1

我有 Spring 表单的 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>

在客户端 timeleft 格式:HH:MM,但在服务器端我们需要将其转换为毫秒(长)。如何做到这一点(来自客户端的Item对象带有(标题、描述、timeleft 字段))?如何转换自定义对象中的特定属性?

我正在尝试做这样的事情:

具有 initBinder 方法的控制器类:

@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]; 参数 [org.springframework.context.support.DefaultMessageSourceResolvable:代码 [item.timeLeft,timeLeft];论据 []; 默认消息 [timeLeft]]; 默认消息 [无法将类型“java.lang.String”的属性值转换为属性“timeLeft”所需的类型“java.lang.Long”;嵌套异常是 java.lang.NumberFormatException: For input string: "12:33"]]

4

0 回答 0