Answer the question
In order to leave comments, you need to log in
For some reason, BindingResult does not catch the error, how can I fix it?
I'm trying to write a project using Spring.
There is a User class whose objects are registered users of the site. The required fields of the User class were marked with annotations from javax.validation.constraints (@NotNull, NotEmpty ).
In the controller, when a post request is made, the User object is marked valid .
I use the thymeleaf template engine, in the html of the page I seem to write everything correctly (I use working training examples).
But in the controller, the error is not caught when I send empty fields in the request.
How can I fix it and what am I doing wrong?
@Entity
@Table(name = "t_user")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "Message Text")
@NotEmpty(message = "Message Text")
@NotBlank(message = "Message Text")
@Min(value = 4, message = "User should enroll to minimum 4 subjects!!")
private String username;
@NotNull
@NotEmpty
@NotBlank(message = "Message Text")
private String password;
@Transient
private String passwordConfirm;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles;
public User() {
}
public User(String username, String password, String passwordConfirm) {
this.username = username;
this.password = password;
this.passwordConfirm = passwordConfirm;
}
}
@Controller
public class RegistrationController {
@Autowired
private UserService userService;
@GetMapping("/registration")
public String registration(Model model) {
model.addAttribute(new User());
return "registration";
}
@PostMapping("/registration")
public String addUser(@Valid User user, BindingResult bindingResult, Model model) {
System.out.println(bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
if (!user.getPassword().equals(user.getPasswordConfirm())) {
model.addAttribute("passwordError", "Пароли не совпадают");
return "registration";
}
if (!userService.saveUser(user)) {
model.addAttribute("usernameError", "Пользователь с таким именем уже существует");
return "registration";
}
return "redirect:/blog";
}
}
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Вход</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Регистрация пользователя</title>
</head>
<body>
<header th:insert="blocks/header :: header"></header>
<div class="container mt-5 mb-5">
<h1>Регистрация пользователя</h1>
<form role="form" action="/registration" th:action="@{/registration}" th:object="${user}" method="post" >
<div class="form-group">
<div class="col-lg-12">
<th:block th:if="${#fields.hasErrors('${user.*}')}">
<div th:utext="Common error message">Alert</div>
</th:block>
<div class="form-group input-group" th:classappend="${#fields.hasErrors('username')}? 'has-error'">
<input type="text" th:field="*{username}" class="form-control" placeholder="username" />
<span class="help-block" th:if="${#fields.hasErrors('username')}" th:errors="*{userName}">Incorrect title</span>
</div>
<div class="form-group input-group" th:classappend="${#fields.hasErrors('password')}? 'has-error'">
<input type="text" th:field="*{password}" class="form-control" placeholder="password" />
<span class="help-block" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Incorrect title</span>
</div>
<div class="form-group input-group" th:classappend="${#fields.hasErrors('passwordConfirm')}? 'has-error'">
<input type="text" th:field="*{passwordConfirm}" class="form-control" placeholder="passwordConfirm" />
<span class="help-block" th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}">Incorrect title</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Зарегистрироваться</button>
</div>
</div>
</div>
</form>
</div>
</body>
<div th:insert="blocks/footer :: footer"></div>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Hello!
First of all, a small recommendation - instead of directly getting the User object from the view and saving it, create a UserDto class and then, after receiving the data from the view, map it to User ().
For possible validation errors, have a look at this link - https://stackoverflow.com/questions/42423553/sprin...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question