【问题标题】:Spring boot + Thymeleaf + ajax cannot send VO or DTO ControllerSpring boot + Thymeleaf + ajax 无法发送 VO 或 DTO Controller
【发布时间】:2020-12-29 13:25:21
【问题描述】:

我尝试通过 thymeleaf + ajax 将表单数据发送到 Java 控制器。 但是在ReplyDto,无法接收数据。

这是我的代码。

Themeleaf,Ajax .html

function insertReply() {
    $.ajax({
        type: 'POST',
        url: '/reply/insertReply',
        data: $("#replyForm").serialize(),
        contentType: "application/json",
        success: function(data) {
            alert("test");
        },
        error: function(request, status, error) {
            alert("Error : " + error + "\nStatus : " + status + "\nRequest : " + request);
        }
    });
}

    <form id="replyForm" th:object="${replyDto}" th:method="post">
        <input type="hidden" th:field="${post.postNo}" th:value="${post.postNo}">
        
        <input class="form-control" type="text" th:field="*{replyTitle}" placeholder="replyTitle">
        <textarea class="form-control" th:field="*{replyContent}" placeholder="insert" id="replyContentData" style="height: 100px"></textarea>
        <button class="btn btn-primary" id="replyInsertButton" type="button" onclick='insertReply()'>댓글 입력</button>
    </form>

ReplyDto.java

private int replyNo;
private String replyTitle;
private String replyContent;
private int postNo;

ReplyContoller.java

@PostMapping("/insertReply")
public int insertReply(ReplyDto replyDto) {
    System.out.println(replyDto.getPostNo());
    System.out.println(replyDto.getReplyTitle());
    System.out.println(replyDto.getReplyContent());
    return replyService.insertReply(replyDto);
}

Controller 有注解@RestController。 在控制台,记录 0、null、null 每个 postNo、replyTitle、replyContent。

如何将表单数据发送到 Controller? 请帮忙!

【问题讨论】:

    标签: java ajax spring-boot thymeleaf


    【解决方案1】:
    1. 你不见了@RequestBody

      public int insertReply(@RequestBody ReplyDto replyDto) { ...

    2. $("#replyForm").serialize() 将表单转换为查询字符串。您需要有效的 JSON

    您可能应该寻求这样的解决方案:Spring RestController POST accepting a basic HTML form

    如果您坚持使用当前的解决方案:

    当修复缺少@RequestBody 时,首先在 Postman 中验证控制器。

    将表单转换为 JSON:

    【讨论】:

    • 谢谢。我使用@RequestBody 解决了。并将序列化数据更改为 JSON.stringfy($("#replyForm").serialize())。但是又产生了一个错误。
    • org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法'POST'
    • 我使用了form-method:post,ajax type:post,在Controller处接收@PostMapping。
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2019-02-26
    • 2019-06-11
    • 2020-10-19
    • 2018-07-17
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多