猿问

弹簧启动控制器无法识别来自 ajax 的数据

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


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


单击提交按钮时,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);

}

我传递的 json,我可以看到与 a 如下:console.log()


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

在IJ控制台中,我得到了这个爪哇警告:


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


斯蒂芬大帝
浏览 123回答 2
2回答

四季花海

问题是你正在使用它从URL中获取参数,你应该用于POST请求@RequestParam@RequestBody我建议创建一个DTO对象,您可以使用它来读取POST请求的正文,如下所示:public ResponseEntity<String> checkLogin(@RequestBody UserDTO userDTO){DTO 是这样的:public class UserDTO {&nbsp; private String email;&nbsp; private String password;&nbsp; //getter & setters}

米琪卡哇伊

您可以遵循以下方法:使用内容类型:“应用程序/json;字符集 = utf-8“,创建一个域对象,该对象是电子邮件和密码的包装器,并使用@RequestBody读取 jsonpublic class Login{&nbsp;private String email;&nbsp;private String password;&nbsp;//Getters and Setters}@RequestMapping("/checkLoginAdministrator")public ResponseEntity<String> checkLogin((@RequestBody Login login) {&nbsp;//logic}
随时随地看视频慕课网APP

相关分类

Java
我要回答