繁体   English   中英

无法在 Spring 中提交 LocalTime 列表

[英]Unable to submit list of LocalTime in Spring

我有一个包含对象列表的实体(省略了 getter 和 setter 以及此示例的所有无关代码)

public class SampleType {
    @OneToMany
    List<SampleTypeTime> sampleTypeTimes = new ArrayList<SampleTypeTime>();
}

public class SampleTypeTime {
    @DateTimeFormat(iso = ISO.TIME)
    LocalTime time;
}

我有这个表格,允许用户选择多个小时..

<form th:object="${sampleType}" th:method="POST" th:action="@{#}">
    <select th:field="*{sampleTypeTimes}" type="time" class="form-control" multiple>
        <option th:value="00:00" th:text="${"00:00"}"></option>
        <option th:value="01:00" th:text="${"01:00"}"></option>
        ... and so on
    </select>
</form>

我的控制器:

@PostMapping("sampletype/")
public String productsTypesPost(@ModelAttribute SampleType sampleType, Model model) {
    sampleTypeRepository.save(sampleType);
    return "sampletype";
}

当我提交表单时,我收到以下错误消息:

Field error in object 'sampleType' on field 'sampleTypeTimes': rejected value [00:00,02:00];
codes [typeMismatch.sampleType.sampleTypeTimes,typeMismatch.sampleTypeTimes,typeMismatch.java.util.List,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sampleType.sampleTypeTimes,sampleTypeTimes];
arguments []; default message [sampleTypeTimes]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 'sampleTypeTimes';
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.example.project.SampleTypeTime' for property 'sampleTypeTimes[0]': no matching editors or conversion strategy found]

在我看来,它很难将 String[] 转换为 List,我该如何解决这个问题?

编辑:添加控制器类

正如我在评论中所说, form 返回String值,而数组包含SampleTypeTime实例。 您需要告诉 Spring 如何将String转换为SampleTypeTime 为此,您必须创建PropertyEditor实现:

public class SampleTypeTimeEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        LocalTime time = LocalTime.parse(text);
        SampleTypeTime sampleTime = new SampleTypeTime();
        sampleTime.setTime(time);
        setValue(appointment);
    }
}

在这个示例代码片段中,我不检查文本是否具有正确的格式。 但在实际代码中,您当然应该这样做。 之后,将创建的属性编辑器添加到控制器的DataBinder中:

@Controller
public class FormController {

    @InitBinder
    public void initBinder(DataBinder binder)        
        binder.registerCustomEditor(SampleTypeTime.class, new SampleTypeTimeEditor());
    }       

    ... 
}

现在 Spring 会自动将String转换为SampleTypeTime 您可以从官方文档的这一章中获取有关PropertyEditor更多信息。 在这里您可以获得有关DataBinder详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM