如何将Java Spring time属性绑定到Thymeleaf字段?

我有一个Java时间属性绑定到Thymeleaf字段的问题 .

这是我的HTML代码

<input th:field="*{startTime}" type="text"/>
<script>
    $("#startTime").timepicker({
        showSeconds: true,
        showMeridian: false,
        secondStep: 1

    });
</script>

这是我的模型属性代码

@NotNull(message = "Start time cannot be empty")
private Time startTime;

public Time getStartTime() {
    return startTime;
}

public void setStartTime(Time startTime) {
    this.startTime = startTime;
}

当我提交表格时,我得到了例外

Failed to convert property value of type java.lang.String to required
type java.sql.Time for property startTime; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type java.lang.String to type
@javax.validation.constraints.NotNull
@org.springframework.format.annotation.DateTimeFormat java.sql.Time
for value 14:15:41; nested exception is
org.joda.time.IllegalFieldValueException: Cannot parse "14:15:41":
Value 14 for clockhourOfHalfday must be in the range [1,12]

如果我插入12小时的时间,我得到了这个例外

Failed to convert property value of type java.lang.String to required type java.sql.Time for property startTime; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull
@org.springframework.format.annotation.DateTimeFormat java.sql.Time for value 11:15:41; nested exception is
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type org.joda.time.DateTime to type @javax.validation.constraints.NotNull @org.springframework.format.annotation.DateTimeFormat java.sql.Time

如何将Spring Time属性绑定到Thymeleaf字段?

回答(1)

3 years ago

创建一个Property type String并创建get set方法并绑定到view

private String startTimeString;

和控制器端将值String转换为Time并设置它

setStartTime(Time.valueOf(ModelName.getstartTimeString()));