简体   繁体   中英

Spring-Boot Controller does not recognize data from ajax

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":"fantasticemail@email.it","password":"1234"}

In the IJ console I get this java WARN:

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

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
}

You can either follow the below approaches:

  1. Use the contentType: "application/json; charset=utf-8",

  2. 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM