0
사용자 정의 주석 유효성 검사기에서 catch 한 유효성 검사 오류를 표시하지 않는 Thymeleaf 레이아웃에 문제가 있습니다.스프링 부트 Thymeleaf 사용자 정의 유효성 검사기에서 오류를 표시하지 않습니다.
CONTROLLER :
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String handleRegisterForm(@ModelAttribute("userCreateForm") @Valid UserCreateForm userCreateForm, BindingResult bindingResult, Model model){
LOGGER.debug("Processing user create form={}, bindingResult={}", userCreateForm, bindingResult);
model.addAttribute("userCreateForm", new UserCreateForm());
model.addAttribute("email", userCreateForm.getEmail());
model.addAttribute("password", userCreateForm.getPassword());
model.addAttribute("firstName", userCreateForm.getFirstName());
model.addAttribute("lastName", userCreateForm.getLastName());
userCreateFormValidator.validate(userCreateForm, bindingResult);
if (bindingResult.hasErrors()){
for (int i = 0; i < bindingResult.getAllErrors().size(); i++)
{
System.out.println(bindingResult.getAllErrors().get(i).getObjectName());
System.out.println(bindingResult.getAllErrors().get(i).getCode());
System.out.println(bindingResult.getAllErrors().get(i).toString());
}
return "register";
}
try {
userService.create(userCreateForm);
} catch (DataIntegrityViolationException | NoSuchAlgorithmException e) {
bindingResult.reject("email.exists", "Email already exists");
LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate email", e);
}
return "redirect:/login";
}
MODEL :
public class UserCreateForm {
@NotEmpty
@UniqueEmail
private String email;
@NotEmpty
private String password;
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
VALIDATOR :
@Documented
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmailValidator.class)
public @interface UniqueEmail {
String message() default "Account exists!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
private UserRepository userRepository;
public UniqueEmailValidator(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void initialize(UniqueEmail uniqueEmail) {
}
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
return email != null && !userRepository.findOneByEmail(email).isPresent();
}
}
THYMELEAF의 CODE :
<div class="container" >
<div class="row view-area">
<div class="col-lg-12">
<form role="form" name="userCreateForm" th:object="${userCreateForm}" th:action="@{/register}" method="post">
<div class="row form-group">
<div class="col-lg-6">
<label for="email" class="sr-only">EMAIL</label>
<input type="text" th:field="*{email}" id="email" class="form-control" placeholder="EMAIL" required="required" autofocus="autofocus" />
<p th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">ERROR!</p>
</div>
</div>
이 내 콘솔 출력 할 때 유효성 검사기 캐치 오류 :
userCreateForm
UniqueEmail
Field error in object 'userCreateForm' on field 'email': rejected value
[[email protected]]; codes [UniqueEmail.userCreateForm.email,UniqueEmail.email,UniqueEmail.java.lang.String,UniqueEmail]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userCreateForm.email,email]; arguments []; default message [email]]; default message [Account exists!]
그래서 당신은 내 검증 캐치 오류를 확인하고 페이지를 새로 고침 할 수있다. 그러나 그 후에 오류는 보이지 않습니다. 내 Thymeleaf 코드에 문제가 있다고 생각하지만 어딘가에 있습니다.
당신이 혼합 '이메일'과 'FIRSTNAME'하지 적이 있습니까? –