如何在 Spring 引导中将参数从 Ajax 传递到 RestController

How to pass Parameter from Ajax to RestController in Spring Boot

我尝试将参数从 Ajax 传递给 RestController 以发送电子邮件。

就是Controller Post发送Enail的方法

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String create(@RequestParam("covere") String covere, @RequestParam("title") String title,
            @RequestParam("username") String username, @RequestParam("usernameto") String usernameto) {
        try {
            mailService.sendMail(covere, title, username, usernameto);
            return "sendmail";
        } catch (MailException e) {
            e.printStackTrace();
        }
        return "sendmail";
    }

也就是Ajax调用Post传递Variable来发送Message

$("#vuta").on("click", function(e) {
    var EmailData = {
              "covere" : "John",
              "title" :"Boston",
              "username" :"test@yahoo.fr",
              "usernameto" :"test@yahoo.fr"
           }

$.ajax({
    type: "POST",
    url: "/emailsend",
    dataType : 'json',
    contentType: 'application/json',
    data: JSON.stringify(EmailData)
});
});

我在发送电子邮件时遇到此错误

Required String parameter 'covere' is not present","path":"/emailsend"}

感谢帮助

您的控制器需要通过查询字符串获得参数。您可以使用 $.param 将对象格式化为查询字符串并将其发送到 URL:

$("#vuta").on("click", function(e) {
        var EmailData = {
            "covere" : "John",
            "title" :"Boston",
            "username" :"test@yahoo.fr",
            "usernameto" :"test@yahoo.fr"
        }

        $.ajax({
            type: "POST",
            url: "/emailsend?" + $.param(EmailData),
            dataType : 'json',
            contentType: 'application/json'
        });
});