我怎么知道spring-web
无需使用 getter/setter 即可验证我的 dto?
@PostMapping(path = "/test")
public void test(@Valid @RequestBody WebDTO dto) {
}
public class WebDTO {
@Valid //triggers nested validation
private List<Person> persons;
//getter+setter for person
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public static class Person {
@NotBlank
public String name;
public int age;
}
}
Result:
"java.lang.IllegalStateException","message":"JSR-303 validated property
'persons[0].name' does not have a corresponding accessor for Spring data
binding - check your DataBinder's configuration (bean property versus direct field access)"}
特殊要求:我还想补充@AssertTrue
在布尔 getter 上提供跨域验证,例如:
@AssertTrue
@XmlTransient
@JsonIgnore
public boolean isNameValid() {
//...
}
您必须配置 Spring DataBinder 以使用直接字段访问。
@ControllerAdvice
public class ControllerAdviceConfiguration {
@InitBinder
private void initDirectFieldAccess(DataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)