我如何在Spring MVC中验证另一个对象(DTO)的引用对象

时间:2017-04-21 11:28:43

标签: spring spring-mvc hibernate-validator modelattribute

  

我的UserDto课程在这里:

package com.carpoint.dto;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

import com.carpoint.validation.annotation.PasswordMatches;

@PasswordMatches
public class UserDto{

    @NotEmpty
    private String username;

    @NotEmpty @Size(min=6, max=30)
    private String password;

    @NotEmpty
    private String confirmPassword;

    @NotEmpty
    private String firstname;
    @NotEmpty
    private String lastname;
    @NotEmpty @Email
    private String email;

    private UserAddressDto userAddress;

    //getters & setters
}
  

和UserAddressDto这里的课程:

package com.carpoint.dto;

import org.hibernate.validator.constraints.NotEmpty;

public class UserAddressDto {

    @NotEmpty
    private String address;
    @NotEmpty
    private String country;
    @NotEmpty
    private String city;
    @NotEmpty
    private Integer pincode;

        //getters & setters
    }

我的问题是UserDto上的验证工作成功,但它不是UserAddressDto的引用类型,我想验证UserDto的引用类型有什么办法吗?

  

,这是我的UserController代码段:

 @RequestMapping(value = "/add", method = RequestMethod.POST)
        public String addUsers(@Valid @ModelAttribute("userDto")UserDto userDto, 
ModelMap model, SessionStatus status, RedirectAttributes attributes) 
throws IOException {
    ....
    ....
    }

1 个答案:

答案 0 :(得分:0)

您是否尝试将@Valid放在课程private UserAddressDto userAddress;上的UserDto上?我想这应该足够了,因为Spring自己处理它。