Yousef
Yousef

Reputation: 385

Postman post call to spring is always null for 2 out of 5 constructor parameters

I apologize in advance because I wasn't sure how to phrase the question. I have the below class:

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;

@Column(name = "username", length = 30)
private String username;

@Column(name = "email", length = 60)
private String email;

@Column(name = "birthday", length = 40)
private Date birthday;

@Column(name = "password", length = 60)
private String password;

@Column(name = "profilepic", length = 60)
private String profilePic;

public User() {
}

public User(String username, String email, String password, Date birthday, String profilePic) {
    this.username = username;
    this.email = email;
    this.password = password;
    this.birthday = birthday;
    this.profilePic = profilePic;
}


public long getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getProfilePic() {
    return profilePic;
}

public void setProfilePic(String profilePic) {
    this.profilePic = profilePic;
}
}

and then in the UserController class I have an addUser method:

@RequestMapping("/api")
@RestController
public class UserController {

private final UserRepository userRepository;

@Autowired
public UserController(UserRepository userRepository) {
    this.userRepository = userRepository;
}


@RequestMapping(method = RequestMethod.POST)
public ResponseEntity addUser(@ModelAttribute User user) {
    userRepository.save(user);

    return new ResponseEntity("User Created!", HttpStatus.OK);
}

@GetMapping
public List<User> getAllUsers() {
    return userRepository.findAll();
}

}

When I send a postman request as form-data or as form-urlencoded, it saves a new user but username and profilepic are always null. I double checked the spelling over 15 times by now so I don't think that's it. Why are those 2 always null?

postman body

Upvotes: 0

Views: 771

Answers (1)

igorepst
igorepst

Reputation: 1240

Because in your Postman body you use user_name and profilepic instead of username and profilePic. Also add the setter for the username:

public void setUsername(String username) {
    this.username = username;
}

Upvotes: 2

Related Questions