【问题标题】:Spring-Boot Controller does not recognize data from ajaxSpring-Boot Controller 无法识别来自 ajax 的数据
【发布时间】:2019-04-08 19:07:06
【问题描述】:

我正在尝试将 json(电子邮件和密码)从 ajax 发送到 Spring-Boot 中的控制器方法。

我确定我从 html 中获取数据并以正确的方式解析为 json,但控制器仍然说缺少电子邮件预期字段。 我也使用了form.serialized(),但没有任何改变,所以我决定创建自己的对象,然后将其解析为 json。

单击提交按钮时开始 Ajax 调用:

function login() {
var x = {
    email : $("#email").val(),
    password : $("#password").val()
  };
$.ajax({
    type : "POST",
    url : "/checkLoginAdministrator",
    data : JSON.stringify(x),
    contentType: "application/json",
    dataType: "json",
    success : function(response) {
        if (response != "OK")
            alert(response);
        else
            console.log(response);
    },
    error : function(e) {
        alert('Error: ' + e);
      }
});

这是控制器内部的方法:

@RequestMapping("/checkLoginAdministrator")
public ResponseEntity<String> checkLogin(@RequestParam(value = "email") String email,
                                         @RequestParam(value = "password") String password) {
    String passwordHashed = Crypt.sha256(password);

    Administrator administrator = iblmAdministrator.checkLoginAdministrator(email, passwordHashed);

    if (administrator != null) {
        Company administratorCompany = iblmCompany.getAdministratorCompany(administrator.getCompany_id());

        String administratorCompanyJson = new Gson().toJson(administratorCompany);

        return new ResponseEntity<String>(administratorCompanyJson, HttpStatus.OK);
    }
    return new ResponseEntity<String>("{}", HttpStatus.OK);
}

我通过console.log() 可以看到的json 如下:

{"email":"fantasticemail@email.it","password":"1234"}

在 IJ 控制台中,我得到了这个 java WARN:

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'email' is not present]

【问题讨论】:

  • 当您指示 ajax 将发送 contentType application/json 时,为什么要发送字符串(通过对 JSON 进行字符串化)?此外,在您的代码中,如果您使用“GET”,您期望得到一个参数;但是,您使用的是“POST”,因此您应该检查 @RequestBody。

标签: javascript java ajax spring-boot


【解决方案1】:

问题是您使用的是@RequestParam,它从网址获取参数,您应该使用@RequestBody 进行POST 请求

我建议创建一个 DTO 对象,您可以使用它来读取 POST 请求的正文,如下所示:

public ResponseEntity<String> checkLogin(@RequestBody UserDTO userDTO){

DTO 是这样的:

public class UserDTO {
  private String email;
  private String password;

  //getter & setters
}

【讨论】:

    【解决方案2】:

    您可以遵循以下方法:

    1. 使用 contentType:“application/json;charset=utf-8”,

    2. 创建一个域对象,它是电子邮件和密码的包装器,并使用 @RequestBody 读取 json

      public class Login{
       private String email;
       private String password;
       //Getters and Setters
      }
      
      
      
      @RequestMapping("/checkLoginAdministrator")
      public ResponseEntity<String> checkLogin((@RequestBody Login login) {
       //logic
      }
      

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2021-09-07
      • 1970-01-01
      • 2015-09-25
      • 2019-02-26
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多