Spring Boot Thymeleaf 自定义验证器不显示错误
Posted
技术标签:
【中文标题】Spring Boot Thymeleaf 自定义验证器不显示错误【英文标题】:Spring Boot Thymeleaf custom validator not showing errors 【发布时间】:2018-05-07 18:49:05 【问题描述】:我的 Thymeleaf 布局有问题,它没有显示自定义注释验证器捕获的验证错误。
控制器:
@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";
型号:
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;
验证者:
@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();
百里香代码:
<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
[test@test.com]; 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'和'email'混为一谈吗? 【参考方案1】:就像评论中提到的那样。在您的 tymeleaf 模板中,您的错误消息的属性名称错误。
不正确:
<p th:if="$#fields.hasErrors('firstName')" th:errors="*firstName">ERROR!</p>
正确:
<p th:if="$#fields.hasErrors('email')" th:errors="*email">ERROR!</p>
【讨论】:
以上是关于Spring Boot Thymeleaf 自定义验证器不显示错误的主要内容,如果未能解决你的问题,请参考以下文章
spring boot + thymeleaf +security自定义规则 的简单使用
Spring Boot + Websocket + Thymeleaf + Lombok
springboot 学习 —— springboot 2.x ,thymeleaf 自定义 select 标签