简体   繁体   中英

form validation in spring in action 5

I am following the source code of spring in action 5 on github, and I code my own version. When I leave the name blank and commit, I get a wrong page like that

在此处输入图片说明

and the console output is: Field error in object 'taco' on field 'name': rejected value [];

But the correct page is like that: taco 设计页面,名称文本框周围带有警告消息

here is my code:

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;

Where is the problem

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

solution:

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

conclusiong:

The parameter Erroes errors must behide the valid object parameter, here is Taco taco

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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