【问题标题】:Spring Boot error message doesn't workSpring Boot 错误消息不起作用
【发布时间】:2018-09-07 09:32:57
【问题描述】:

我正在编写我的第一个 Spring Boot 应用程序,但我遇到了这个问题。我无法向用户显示错误消息。没有该数据的对象不会保存在数据库中,这没关系。但显示错误消息是问题所在。当我调试时,我得到错误大小 = 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";
}

百里香

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

【问题讨论】:

  • 您的输入字段应该有th:field="*{address}" 而不是name 属性。 tis 与 Thymeleaf 进行适当的绑定。

标签: java spring validation spring-boot thymeleaf


【解决方案1】:

您是否在@SpringBootApplication 中定义了Validator

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }
}

【讨论】:

  • 不,我没有。我不熟悉验证器。你能给我一些关于验证器的提示吗?
  • 您不需要它,因为它是开箱即用的配置,验证也在工作和设置,因为保存实体失败(可能是由于验证)。
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 2019-08-22
  • 1970-01-01
  • 2021-02-27
  • 2021-07-16
  • 1970-01-01
  • 2015-11-13
  • 2017-12-28
相关资源
最近更新 更多