0

I designed a controller that receives a Json from frontend. The controller is called properly.
When I print the elements of that Json to console, they become "null".

The frontend sends the json {'username':"abc", "password":123 } to backend. The controller is called properly but the values of 'username' and 'password' become null when I print them to console.

The Json sent from frontend {'username':'abc', 'password':12345 }. The request url of frontend is http://my_ip_address:port/login/

Here is my code of Controller:

@RestController 
@CrossOrigin("*") 
@RequestMapping( value="login", produces="application/json" ) 
public class LoginController{ 

    @PostMapping(value="/", consumes="application/json") 
    @ResponseStatus( HttpStatus.OK ) 
    public void SignIn( Members member ){ 

        System.out.println("username:"+member.getUsername() + 
                           "\npassword: "+member.getPasssword() ); 
        // The values of Json become null!!!.

    } 
} 

Here is my Members:

public class Members{ 
    private String username; 
    private String password; 

    /* omit setters and getters */ 
} 

I have tried to add @RequestBody to the method but it turns out to be Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing.

I am confused by the results. In fact, I got the expected result at the first time. But when I restarted the project again, it becomes so weird.



UPDATE.

Problem fixed.

  • Add @RequestBody to the method.
  • The problem is that I forgot to put the data into body of HTTP request. It passed "null" values to backend.

1 Answers1

2

You forgot to add @RequestBody:

@PostMapping(value="/", consumes="application/json") 
@ResponseStatus( HttpStatus.OK ) 
public void SignIn(@RequestBody Members member ){ 

    System.out.println("username:"+member.getUsername() + 
                       "\npassword: "+member.getPasssword() ); 
    // The values of Json become null!!!.

} 

It turns out that you do not need to use consumes attribute. It comes as default.

Prashant
  • 4,775
  • 3
  • 28
  • 47
  • Yes, I tried it before. But the console returns ```Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing. ``` – wukaihua119 Sep 13 '19 at 11:20
  • Were you able to make a request via POSTMAN? – Prashant Sep 13 '19 at 11:22
  • I just used POSTMAN to make a request. The result of the response is still ```{"username":null,"password":null}```. – wukaihua119 Sep 13 '19 at 14:09