提交表单时,带有日期/时间的 Spring 为空

我的控制器中有两个映射。这是一个 GET 映射:


@RequestMapping(value="/items/book-list/edit", method = RequestMethod.GET)

public String showEditBookPage(@RequestParam Long id, ModelMap model){

    Book book = bookService.findBookById(id);

    model.addAttribute("editForm", book);

    LOG.info("Logged modified date once page is loaded: " + book.getModifyDate());

    return "admin/book";

}

此映射仅用于显示小窗体的 book.jsp 页面。


我还有另一个具有相同值但使用 POST 方法的映射,用于提交表单。


 @RequestMapping(value="/items/book-list/edit", method = RequestMethod.POST)

public String updateBook(@ModelAttribute("editForm") @Valid Book bookForm, BindingResult result, ModelMap model){

    if(result.hasErrors()){

        return "/admin/book";

    }


    LOG.info("Logged modified date before Save object: " + bookForm.getModifyDate());

    LOG.info("Logged author before Save object: " + bookForm.getAuthor());


    bookService.saveBook(bookForm);


    LOG.info("Logged modified date after Save object: " + bookForm.getModifyDate());

    LOG.info("Logged author after Save object: " + bookForm.getAuthor());


    return "admin/book";

}

我的书.jsp:


<form:form method="post" modelAttribute="editForm" >

        <div class="row border py-4">

            <div class="col-sm-6">

                <spring:bind path="title">

                    <div class="form-group">

                        <form:label path="title" for="title">Book title</form:label>

                        <form:input path="title" type="text" class="form-control" id="title" cssErrorClass="form-control border border-danger"/>

                    </div>

            </div>

    </form:form>


叮当猫咪
浏览 71回答 3
3回答

波斯汪

尝试为该LocalDateTime字段显式添加反序列化器:@JsonDeserialize(using = LocalDateTimeDeserializer.class)&nbsp;&nbsp;@CreationTimestamp@Column(name="create_date", updatable = false, nullable = false)private LocalDateTime createDate;还有你的反序列化类:public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public LocalDate deserialize(JsonParser jsonParser, DeserializationContext ctx)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws IOException, JsonProcessingException {&nbsp; &nbsp; &nbsp; &nbsp; // parse the String date into LocalDateTime object as it fits you&nbsp; &nbsp; }}

UYOU

您忘记在 My book.jsp: 中添加 modify_date 字段,因为只有字段日期会发布,因为它是新请求,而您保存在模型中的所有旧字段都不会随请求一起发布。所以有两个选项添加输入文本字段来更改日期。或者您将在保存之前手动设置日期&nbsp;bookForm.setModifyDate(new Date());&nbsp;bookService.saveBook(bookForm);&nbsp;或者你也可以添加 @UpdateTimestamp 如果你想加仑本地日期和时间@UpdateTimestampprivate LocalDateTime modifyDate;

浮云间

@UpdateTimestampprivate LocalDateTime modifyDate;这将完成工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java