【问题标题】:Form validation in spring with thymeleaf春季使用百里香进行表单验证
【发布时间】:2018-05-19 20:50:38
【问题描述】:

我擅长使用 spring boot 和 thymeleaf 进行表单验证,但我遇到了问题:我无法使用两个 @ModelAttribute 字段在表单中进行验证。像 spring 官方网站的表单验证这样的示例可以正常工作,但是当我在帖子中添加两个 @model 属性时,我在网页上只得到错误,并且没有像 spring 示例中那样的表单提示。

控制器类:

@Controller
public class MyController {

    @Autowired
    InstructorRepository instructorRepository;

    @Autowired
    DetailRepository detailRepository;

    @GetMapping("/index")
    public String mainController(){
        return "index";
    }

    @GetMapping("/add")
    public String addInstructorForm(Model model){
        model.addAttribute("instructor", new Instructor());
        model.addAttribute("detail", new InstructorDetail());
        return "addInstructor";
    }

    @PostMapping("/add")
    public String submitForm(@Valid @ModelAttribute Instructor instructor, @ModelAttribute InstructorDetail instructorDetail, BindingResult bindingResult1){
       /* if (bindingResult.hasErrors()) {
            return "instructorsList";
        }
        instructor.setInstructorDetail(instructorDetail);
        instructorRepository.save(instructor);*/

        if (bindingResult1.hasErrors()) {
            return "addInstructor";
        }
        return "redirect:/instructorsList";
    }

    @GetMapping("/instructorsList")
    public String getList(Model model){
        Map map = new HashMap<>();
        List list = new ArrayList<Instructor>();
        list = instructorRepository.findAll();
        List resultList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Instructor instructor = (Instructor)list.get(i);
            InstructorDetail detail = detailRepository.getInstructorDetailById(instructor.getId());
            InstructorAndDetail iid = new InstructorAndDetail(instructor, detail);
            resultList.add(iid);
        }
        model.addAttribute("instructors", resultList);
        return "instructorsList";
    }

}

html表单sn-p:

<form action="#" data-th-action="@{/add}" data-th-object="${instructor}" method="post">
   <div class="form-group">
        <label for="1">First name</label>
        <input class="form-control" id="1" type="text" data-th-field="${instructor.firstName}" placeholder="John"/>
        <div data-th-if="${#fields.hasErrors('firstName')}" data-th-errors="${instructor.firstName}">name error</div>
   </div>

【问题讨论】:

标签: spring forms validation spring-mvc thymeleaf


【解决方案1】:

还有下一个问题:然后我将实体添加到 thymeleaf 表单中我只传递了 2 个字段(或之后的一个字段),但是有 3 个字段带有

@NotNull
@Size(min=2, max=30)

所以当我在我的代码中评论它们时,单字段验证开始起作用:)。 如果您遇到同样的问题,请检查类中标记为 @Valid 注释的所有字段是否都反映在您的表单中。 (或者有默认的有效值?UPD:如果它们没有表单镜像,则不要使用有效的默认值)

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2019-01-05
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多