在春季进行表格验证5

时间:2020-02-23 13:37:59

标签: java spring-mvc

我正在github上使用 spring in action 5 的源代码,并编写自己的版本。 当我将名称保留为空白并提交时,会出现类似这样的错误页面

enter image description here

,控制台输出为: Field error in object 'taco' on field 'name': rejected value [];

但是正确的页面是这样的: the taco design page with a warning message aroud the name text box

这是我的代码:

design.html

 <label>give it a name:</label>

 <input type="text" th:field="*{name}">

  <span class="validationError"
      th:if="${#fields.hasErrors('name')}"
      th:errors="*{name}">Name Error</span>

designController.java

    @PostMapping
    public String postTaco(@Valid Taco taco, Order order, Errors errors) {
        if (errors.hasErrors()){
            return "design";
        }

        Taco taco1 = tacoRepo.save(taco);
        order.addDesign(taco1);
        return "order";
    }


Taco.java

@Size(min=5, message = "at least 5 characters")
private String name;

1 个答案:

答案 0 :(得分:0)

问题出在哪里

designContrller.java

    @PostMapping
    public String postTaco(@Valid Taco taco, Order order, Errors errors) {
        if (errors.hasErrors()){
            return "design";
        }

        Taco taco1 = tacoRepo.save(taco);
        order.addDesign(taco1);
        return "order";
    }

解决方案:

    @PostMapping
    public String postTaco(@Valid Taco taco, Errors errors, Order order) {
        if (errors.hasErrors()){
            return "design";
        }

        Taco taco1 = tacoRepo.save(taco);
        order.addDesign(taco1);
        return "order";
    }

结论g:

参数Erroes errors必须隐藏在有效的对象参数后面,这里是Taco taco