Michael
Michael

Reputation: 83

Postman Post call to Spring Controller is always null

I have made an application in Spring boot with a database of users. Now i am trying to make a restcall with postman into the controller to send information about an user and save it in the database. The first time the restcall saves a null object in the database (all information is null) instead of the data in the postman call, so i think the error is in the call between postman and the controller.

The entity:

@Entity
@Table(name = "user", schema = "localhost", catalog = "")
public class UserEntity {
    private int userId;
    private int unitId;
    private String roleName;
    private String firstName;
    private String lastName;

The controller:

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/addNewUser",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public String saveNewUser(UserEntity user) {
        try {
            userService.saveNewUser(user);
            return "User has been saved";
        } catch (NullPointerException npe) {
            return "Nullpointer: User has not been saved";
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

The postman call:

The debugger when i send the postman call:

user = {UserEntity@8954} 
userId = 0
unitId = 0
roleName = null
firstName = null
lastName = null

The goal of this project is not to "just make it work" but to make it work in a clean, proper way. That's why i want to use an object to send information instead of putting it in the url parameters.

If anyone can help me out by pointing out what goes wrong, i would be very thankfull. Any tips on code improvement giving the snippers is also very welcome.

Upvotes: 0

Views: 7997

Answers (1)

Alien
Alien

Reputation: 15878

You are passing it as an array which is wrong, pass it like an object.

also You are defining userId,unitId as int in pojo but sending as string in body so change that to "userId":1,"unitId":1 . Pass it like below.

{
  "userId":1,
  "unitId":1,
  "roleName":"AAA",
  "firstName":"BBB",
  "lastName":"CCC"
}

and change public String saveNewUser(UserEntity user) to public String saveNewUser(@RequestBody UserEntity user) by adding @RequestBody.

Update

Adding to that, change your request content type to json enter image description here

Upvotes: 3

Related Questions