我正在嘗試將 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":"[email protected]","password":"1234"}在IJ控制臺中,我得到了這個爪哇警告:Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'email' is not present]
2 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
問題是你正在使用它從URL中獲取參數,你應該用于POST請求@RequestParam@RequestBody
我建議創建一個DTO對象,您可以使用它來讀取POST請求的正文,如下所示:
public ResponseEntity<String> checkLogin(@RequestBody UserDTO userDTO){
DTO 是這樣的:
public class UserDTO {
private String email;
private String password;
//getter & setters
}

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
您可以遵循以下方法:
使用內容類型:“應用程序/json;字符集 = utf-8“,
創建一個域對象,該對象是電子郵件和密碼的包裝器,并使用@RequestBody讀取 json
public class Login{
private String email;
private String password;
//Getters and Setters
}
@RequestMapping("/checkLoginAdministrator")
public ResponseEntity<String> checkLogin((@RequestBody Login login) {
//logic
}
添加回答
舉報
0/150
提交
取消