无法通过Spring启动和Thymeleaf进行验证

时间:2018-03-25 14:09:30

标签: spring spring-boot thymeleaf spring-validator

我正在使用Spring启动和Thymeleaf,我在显示验证错误时遇到问题。这就是我的模型的样子。

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

0 个答案:

没有答案