有 DTO 时如何在 Spring MVC 中进行验证? [英] How to do validation in Spring MVC when there's a DTO?

查看:53
本文介绍了有 DTO 时如何在 Spring MVC 中进行验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个person类和一个personList DTO.DTO 用于将人员对象列表绑定到视图.用户可以编辑一个或多个人,然后单击保存以一次保存所有这些人的编辑.现在我想验证新输入.问题在于控制器代码bindingResults.hasErrors()"不返回用户输入错误.我认为这是因为中间有 personList DTO.似乎它只是检查 personList 类中的错误,而不是像它应该的那样检查 person 类中的错误.如何解决?

I have a person class and a personList DTO. The DTO is used to bind a list of persons object to the view. The user can edit one or more persons and click save to save the edits of all of them at once. Now I want to validate the new input. The problem is that the controller code "bindingResults.hasErrors()" is not returning the user input errors. I think it's because there's the personList DTO in the middle. Seems it is checking just errors in the personList class, but not in the person class as it should. How to fix that?

型号

public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

    @NotEmpty(message="Name must be filled.")
    private String name;

    @Min(value=1900, message="Year is invalid")
    @Max(value=2100, message="Year is invalid")
    private int year;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

}

DTO

public class PersonList {
    
    private List<Person> personList;

    public List<Person> getPersonList() {
        return personList;
    }

    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }
}

查看

<form action="person" method="post" th:object="${personListBind}">
<th:block th:each="person, itemStat : *{personList}">

    Name:
    <input type="text" th:field="*{personList[__${itemStat.index}__].name}" />

    Year:   
    <input type="text" th:field="*{personList[__${itemStat.index}__].year}" />
</th:block>
<input type="submit" name="btnSaveEdit" value="Save"/>

控制器

@RequestMapping(value = "/person", method = RequestMethod.POST)
public ModelAndView editPerson(
   @Valid @ModelAttribute PersonList personList, 
   BindingResult bindingResults) {
        
        
   if(bindingResults.hasErrors()){
      //perform action
   }

推荐答案

找到了解决方案.一个简单的改变.只需要在 DTO 类中添加 @Valid 即可.这是唯一需要更新的行:私人列表<@Valid Person>人名单;

Found the solution for this. One simple change. Just need to add @Valid in the DTO class. This is the only line that needs to be updated: private List<@Valid Person> personList;

这篇关于有 DTO 时如何在 Spring MVC 中进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆