简体   繁体   English

Spring启动验证不起作用

[英]Spring boot validation doesn't work

I have Spring boot application and I can't show error message to user. 我有Spring启动应用程序,我无法向用户显示错误消息。 Object without that data is not saved in the database and that is OK. 没有该数据的对象不会保存在数据库中,这没关系。 But showing error message is the problem. 但显示错误消息是问题所在。 When I debug i get errors size = 0 当我调试我得到错误大小= 0

This is my model: 这是我的模特:

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

Controller 调节器

  @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";

} }

And Thymeleaf 和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>

You need to use @Valid and on some also @ModelAttribute for the parameter of createNewBusiness() - depending on your parameters and stuff. 你需要使用@Valid@ModelAttribute来创建createNewBusiness()的参数 - 这取决于你的参数和东西。

Also you need to add th:field="*{adress}" to your inputfield because it´s the ID of this inputfield in the framework. 您还需要将th:field="*{adress}" adress th:field="*{adress}"到inputfield,因为它是框架中此输入字段的ID。


So in you case the method header will look like this: 所以在你的情况下,方法标题将如下所示:

public String createNewBusiness(@ModelAttribute Business business,
    @Valid Model model, BindingResult result) {
    // ...
}

If you want to throw a custom validation error (for example, if you're validating a field by something other than the annotation validators in your model), you can do that through BindingResult#rejectValue() method. 如果要抛出自定义验证错误(例如,如果您通过模型中的注释验证器以外的其他方式验证字段),则可以通过BindingResult#rejectValue()方法执行此操作。 For example: 例如:

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

Obviously email field is just an example, as you would need that email field on your thymeleaf resource as well as the error field. 显然,电子邮件字段只是一个示例,因为您需要在thymeleaf资源上的电子邮件字段以及错误字段。

More on this topic at 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) 有关此主题的更多信息, 访问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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM