Spring启动验证不起作用

时间:2018-03-26 13:35:17

标签: java validation spring-boot thymeleaf

我有Spring启动应用程序,我无法向用户显示错误消息。没有该数据的对象不会保存在数据库中,这没关系。但显示错误消息是问题所在。当我调试我得到错误size = 0

这是我的模特:

 @Size(min = 1, message = "Address is invalid.")
 @NotNull
 @Column
 private String address;

控制器

  @RequestMapping(value = "/create", method = RequestMethod.POST, 
  consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  public String createNewBusiness(@Valid @ModelAttribute("business") 
  Business business, BindingResult result, Model model) {
  model.addAttribute("userEmail", getUserEmail());
   logger.info("/business/create:" + business.toString());
  LocationResponse locationResponse = geoService.getCoords(business.getAddress());

if(locationResponse.getStatus().equals("OK")) {
    business.setLatitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLat());
    business.setLongitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLng());
    business.setUserId(getUserId());

    businessService.createNew(business);

    model.addAttribute("business", business);

}else{
    business.setAddress(null);
    model.addAttribute("business", business);

}

if(result.hasErrors()){
    List<FieldError> errors = result.getFieldErrors();
    for (FieldError error : errors ) {
        System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
    }
    return "newBusiness";
}

return "business";

}

和Thymeleaf

<div class="input-field left m-0 w-100">
                        <i class="fa fa-map-marker prefix grey-text" aria-hidden="true"></i>
                        <input placeholder="Address" id="inputAddress" name="address" type="text" class="validate my-0" th:required="true">
                        <label th:errors="*{address}" th:if="${#fields.hasErrors('address')}" >Invalid address </label>
                    </div>

2 个答案:

答案 0 :(得分:1)

您需要@Valid使用@ModelAttributecreateNewBusiness()也可以使用th:field="*{adress}"的参数 - 具体取决于您的参数和内容。

此外,您需要将public String createNewBusiness(@ModelAttribute Business business, @Valid Model model, BindingResult result) { // ... } 添加到inputfield,因为它是框架中此输入字段的ID。

因此,在您的情况下,方法标题将如下所示:

geom_raster()

答案 1 :(得分:1)

如果要抛出自定义验证错误(例如,如果您要通过模型中的注释验证器以外的其他方式验证字段),则可以通过BindingResult#rejectValue()方法执行此操作。 例如:

if (business.getEmail()  == null || business.getEmail().length() == 0) {
    result.rejectValue("email", "email.missing", "Must enter email");
}

显然,电子邮件字段只是一个示例,因为您需要在百万美元资源上的电子邮件字段以及错误字段。

有关此主题的更多信息,请访问: https://docs.spring.io/autorepo/docs/spring-framework/3.2.8.RELEASE/javadoc-api/org/springframework/validation/Errors.html#rejectValue(java.lang.String,%20java.lang.String,%20java.lang.Object[],%20java.lang.String)