Spring Controller:对象='invoiceData'的验证失败。错误计数:4

时间:2019-04-02 11:20:10

标签: java spring spring-boot validation thymeleaf

我有两个对象Contractor,其字段为ContractorData,而ContractorData具有类型为Invoice的对象列表:

Contractor
    id
    email
    ContractorData

ContractorData
    id
    FistName
    LastName
    ...
    List<InvoiceData>

对于承包商的更新,我有一个基本的控制器

@GetMapping("/")
public String index(Model model, OAuth2Authentication authentication) {
    String email = String.valueOf(((LinkedHashMap<String, Object>) authentication.getUserAuthentication().getDetails()).get("email"));
    Contractor contractor = contractorRepository.findByEmail(email);
    if (contractor == null) {
        contractor = new Contractor();
        contractor.setEmail(email);
        contractorRepository.save(contractor);
    }
    model.addAttribute("contractor", contractor);
    return "index";
}

和一个更新控制器:

@RequestMapping(value = "/contractor/update/{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
        public String updateContractor(@PathVariable("id") String id, Contractor contractor, Model model) {
        Contractor contractorPO = contractorRepository.findById(id).get();
        ContractorData contractorData = ContractorData.builder()
                .firstName(contractor.getContractorData().getFirstName())
                .lastName(contractor.getContractorData().getLastName())
                .businessName(contractor.getContractorData().getBusinessName())
                .businessLocation(contractor.getContractorData().getBusinessLocation())
                .nip(contractor.getContractorData().getNip())
                .regon(contractor.getContractorData().getRegon())
                .build();
        contractorPO.setContractorData(contractorData);
        contractorRepository.save(contractorPO);
        model.addAttribute("contractor", contractorPO);
        return "index";
    }

这里一切正常。

但是,然后,我有一个控制器指向一个页面,可以在该页面上添加InvoiceData

@RequestMapping(value = "/add/{id}")
public String addPage(@PathVariable("id") String id, Model model) {
    InvoiceData invoiceData = new InvoiceData();
    model.addAttribute("contractorid", id);
    model.addAttribute("invoicedata", invoiceData);
    return "add";
}

以及用于添加发票的控制器:

 @RequestMapping(value = "/addinvoice/{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String addInvoice(@PathVariable("id") String id, InvoiceData data, Model model) {
        Contractor contractor = contractorRepository.findById(id).get();
        contractor.getInvoices().add(data);
        contractorRepository.save(contractor);
        model.addAttribute("contractor", contractor);
        return "index";
    }

在HTML表单方面,index.html的表单如下所示:

 <form action="#" th:action="@{/contractor/update/{id}(id=${contractor.id})}" th:object="${contractor}" method="post">
            <ul class="form-style-1">
                <li>
                    <label>First Name<span class="required">*</span></label>
                    <input type="text" th:field="*{contractorData.firstName}" id="firstName" th:value="${contractor.contractorData?.firstName}">
                </li>
                <li>
                    <label>Last Name<span class="required">*</span></label>
                    <input type="text" th:field="*{contractorData.lastName}" id="lastName" th:value="${contractor.contractorData?.lastName}">
                </li>
                ... and more
                <li>
                    <input type="submit" value="Submit" />
                </li>
    </ul>
</form>

add.html的表单看起来相同,但对象不同:

    <form action="#" th:action="@{addinvoice/{id}(id=${contractorid})}" th:object="${invoicedata}" method="post">
        <ul class="form-style-1">
            <li>
                <label>Reception date<span class="required">*</span></label>
                <input type="date" th:field="*{receptionDate}" id="receptionDate">
            </li>
            ... and more
            <li>
                <input type="submit" value="Submit" />
            </li>
        </ul>
    </form>

问题在于保存InvoiceData。填写表单后,单击“提交”-我收到错误消息:

发生意外错误(类型=错误请求,状态= 400)。 对象=“ invoiceData”的验证失败。错误计数:4

重要编辑

在控制台输出上,我还会收到一个错误:

Field error in object 'invoiceData' on field 'contractDate': rejected value [2019-04-11]; codes [typeMismatch.invoiceData.contractDate,typeMismatch.contractDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [invoiceData.contractDate,contractDate]; arguments []; default message [contractDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'contractDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2019-04-11'; nested exception is java.lang.IllegalArgumentException]

但是正如我之前说的,ContractorData更新表单使一切正常……

1 个答案:

答案 0 :(得分:3)

这里的问题是java.date。 因为在html中,日期的格式为“ yyyy-MM-dd”。你得到错误,因为 春天无法将此日期转换为java.Date。

您可能已经这样声明了接收日期

Date receptionDate;

现在,更改为

    @DateTimeFormat(pattern = "yyyy-MM-dd")
     Date receptionDate;