Reputation: 31
I'm trying to send a json (email and password) from ajax to a Controller method in Spring-Boot.
I'm sure that I'm taking the data from html and parsing in json in the correct way but the controller still says that email expected field is missing.
I also used form.serialized()
but nothing change so I decided to create my own object and then parsing it into json.
Ajax call starts when submit button is clicked:
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);
}
});
This is the method inside the controller:
@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);
}
The json that I pass which I can see with a console.log()
is the following:
{"email":"[email protected]","password":"1234"}
In the IJ console I get this java WARN:
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'email' is not present]
Upvotes: 1
Views: 1530
Reputation: 447
You can either follow the below approaches:
Use the contentType: "application/json; charset=utf-8",
Create a domain object which is a wrapper of email and password and read the json using the @RequestBody
public class Login{
private String email;
private String password;
//Getters and Setters
}
@RequestMapping("/checkLoginAdministrator")
public ResponseEntity<String> checkLogin((@RequestBody Login login) {
//logic
}
Upvotes: 0
Reputation: 461
The problem is you are using @RequestParam
which takes parameters from the url, you should be using @RequestBody
for POST requests
I would recommend creating a DTO object which you can use to read body of the POST request, like this:
public ResponseEntity<String> checkLogin(@RequestBody UserDTO userDTO){
With the DTO being something like this:
public class UserDTO {
private String email;
private String password;
//getter & setters
}
Upvotes: 2