I have thymeleaf view and controller, on /create with GET method I show form with inputs and submit button sends it to /create with POST method. When I submit form controller POST /create triggers but all fields of User are null. Cant get why.
UserController.java
@GetMapping("/create")
public String createUserPage(Model model) {
model.addAttribute("user", new User());
return "create-user";
}
@PostMapping("/create")
public ModelAndView createUser(@ModelAttribute("user") User user) {
userService.addUser(user); // breakpoint, null fields here
return new ModelAndView("redirect:/");
}
create-user.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-
extras-springsecurity3">
<body>
<form th:action="@{/create}" th:method="post" th:object="${user}" >
<div>
<input type="text" name="name" placeholder="name...">
</div>
<div>
<input type="text" name="lastName" placeholder="last name...">
</div>
<div>
<input type="text" name="age" placeholder="age...">
</div>
<div>
<input type="text" name="country" placeholder="country...">
</div>
<div>
<button type="submit">Create</button>
</div>
</form>
</body>
</html>
User.java
@Entity
@Table(name = "user")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "last_name")
private String lastName;
@Column(name = "age")
private int age;
@Column(name = "country")
private String country;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "roles_id")
)
private Set<Role> roles = new HashSet<>();
@Column
private String username;
@Column
private String password;
@Column(name = "is_enabled")
private boolean isEnabled;
public User() {}
@Override
public Collection<Role> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isEnabled() {
return isEnabled;
}
// getters down here
I have thymeleaf view and controller, on /create with GET method I show form with inputs and submit button sends it to /create with POST method. When I submit form controller POST /create triggers but all fields of User are null. Cant get why. (SO says i have too much code)