【问题标题】:how do i validate the referenced object of another object (DTO) in Spring MVC我如何验证 Spring MVC 中另一个对象(DTO)的引用对象
【发布时间】:2017-04-21 11:28:42
【问题描述】:

我的 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 代码 sn-p:

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

【问题讨论】:

    标签: spring spring-mvc hibernate-validator modelattribute


    【解决方案1】:

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

    【讨论】:

    • 您的想法不错,但收到此错误 HTTP 状态 500 - 请求处理失败;嵌套异常是 javax.validation.UnexpectedTypeException:HV000030:找不到约束“javax.validation.constraints.Size”验证类型“java.lang.Integer”的验证器。检查“userAddress.pincode”的配置
    • 那是因为您将 @NotEmpty 用于整数。这是绝对错误的。它仅用于String, Array or Collections。使用@NotNull 作为密码。
    • 非常感谢,最近几天我一直在努力解决这个问题,然后我决定在 stackoverflow 上提问......再次感谢:)
    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多