【问题标题】:How to bind Java Spring time attribute to a Thymeleaf field?如何将 Java Spring 时间属性绑定到 Thymeleaf 字段?
【发布时间】:2015-12-06 11:31:14
【问题描述】:

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 字段?

【问题讨论】:

    标签: java spring time thymeleaf


    【解决方案1】:

    创建一个属性类型String并创建get set方法并绑定到视图

    private String startTimeString;
    

    和控制器端将值字符串转换为时间并设置它

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

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2019-04-27
      • 2011-12-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多