我尝试通过thymelaf+ajax将表单数据发送到Java Controller。但在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);
}
控制器具有注释@RestController。在控制台,日志0,null,null每个postNo,replyTitle,replyContent。
如何将表单数据获取到控制器?请帮忙!
-
您缺少
@RequestBody
public int insertReply(@RequestBody ReplyDto ReplyDto({…
-
$("#replyForm").serialize()
将表单转换为查询字符串。您需要有效的JSON
您可能应该选择这样的解决方案:Spring RestController POST接受基本的HTML表单
如果您坚持使用当前的解决方案:
当修复了丢失的@RequestBody
时,从Postman中验证控制器开始。
将表单转换为JSON:
- https://www.learnwithjason.dev/blog/get-form-values-as-json/
- https://medium.com/@mwakatumbula_/代码-15ecdb18c2ef
- https://css-tricks.com/snippets/jquery/serialize-form-to-json/