如何将 Thymeleaf 的 th:field 值解析为 java.time.Duration?

发布于 2025-01-16 22:39:37 字数 1199 浏览 0 评论 0原文

我在将 th:field 的值解析为 Duration 类的变量时遇到问题。我想要发生的是输入一些数字,我想保存为分钟。

这是来自我的 HTML 文件:

<input type="text" th:field="*{duration}">

在我的对象方面,我刚刚初始化了变量,如下所示:

@Column(nullable = false)
    private Duration duration;

然后我收到一个错误网页:

object='bookingType' 验证失败。错误计数:1 org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1个错误 字段“duration”上对象“bookingType”中的字段错误:拒绝值 [15];代码 [typeMismatch.bookingType.duration,typeMismatch.duration,typeMismatch.java.time.Duration,typeMismatch];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [bookingType.duration,duration];参数[];默认消息[持续时间]];默认消息[无法将类型“java.lang.String”的属性值转换为属性“duration”所需的类型“java.time.Duration”;嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为值“15”的类型 [@javax.persistence.Column java.time.Duration];嵌套异常是 java.lang.IllegalArgumentException:解析尝试失败的值 [15]]

我正在使用 Bootstrap 作为前端,如果它确实重要的话。

我添加了 Thymeleaf 的 java8time extra,尝试将输入类型更改为时间和数字,但仍然遇到相同的错误。

I am having an issue parsing the th:field's value to a variable of class Duration. What I want to happen is to input some numbers and I want to be saved as minutes.

This is from my HTML file:

<input type="text" th:field="*{duration}">

On my object's side, I just initialized the variable like:

@Column(nullable = false)
    private Duration duration;

and I get an error webpage:

Validation failed for object='bookingType'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'bookingType' on field 'duration': rejected value [15]; codes [typeMismatch.bookingType.duration,typeMismatch.duration,typeMismatch.java.time.Duration,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookingType.duration,duration]; arguments []; default message [duration]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.Duration' for property 'duration'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.Duration] for value '15'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [15]]

I am using Bootstrap for the front-end, if it does matter at all.

I added the Thymeleaf's java8time extra, tried changing the input type to time and number, and I still get the same error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ペ泪落弦音 2025-01-23 22:39:37

我通常建议在模型和 Web 界面之间创建 DTO,以便您可以更自由地移动。

可以看到错误和注释中,问题很明显,字符串输入15不是Duration,无法转换。

如果您的 Duration 值是特定类型(分钟、小时...),您可以添加一个自定义转换器,如下所示:

public class StringToDurationConverter
        implements Converter<String, Duration> {

    @Override
    public Duration convert(String from) {
        return Duration.ofMinutes(
                Long.valueOf(from));
    }
}

我们还需要通过以下方式告诉 Spring 这个新转换器:将 StringToDurationConverter 添加到 FormatterRegistry。这可以通过实现 WebMvcConfigurer 并重写 addFormatters() 方法来完成:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDurationConverter());
    }
}

我们使用的默认 Spring 转换器将在每个匹配源上应用转换-目的地对。

如果您想查看有条件的内容:https://stackoverflow.com/a/57539880/2039546

I generally recommend creating DTO's between your models and web interfaces, so you can move more freely.

You can see in the error and comments, the problem is clear, string input 15 is not a Duration and cannot be converted.

If your Duration value is a specific type (minute, hour ..), you can add a custom converter like this:

public class StringToDurationConverter
        implements Converter<String, Duration> {

    @Override
    public Duration convert(String from) {
        return Duration.ofMinutes(
                Long.valueOf(from));
    }
}

We also need to tell Spring about this new converter by adding the StringToDurationConverter to the FormatterRegistry. This can be done by implementing the WebMvcConfigurer and overriding addFormatters() method:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDurationConverter());
    }
}

The default Spring converter we used will apply the conversion on each matching source-destination pair.

If you want to see something conditional: https://stackoverflow.com/a/57539880/2039546

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文