我正在处理错误处理响应映射。在我继续将响应映射到我的域对象之前,我想验证响应。检查错误。
我打算有一个Validator.java类,并为每个API调用实现验证方法。
春天有没有其他方法可以做到这一点?
答案 0 :(得分:0)
package com.people.net;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class UserInfo {
//Unicode check
@Pattern(regexp="[0-9a-zA-Z\\s-]+", message="chars,numbers allowed only")
String name;
int id;
@Pattern(regexp="([0-9]{10})", message="minLength=maxLength=10 only numbers")
String pin;
@Email
String email;
@Size(max=5, message="5 chars max")
String emailType;
@Size(max=5, message="5 chars max")
String addressType;
@Size(max=300, message="5 chars max")
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserInfo(String name, String pin, String id) {
super();
this.id = Integer.parseInt(id);
this.name = name;
this.pin = pin;
}
public UserInfo(int id,String name, String pin, String email, String emailType, String addressType, String address) {
super();
this.id = id;
this.name = name;
this.pin = pin;
this.email = email;
this.emailType = emailType;
this.addressType = addressType;
this.address = address;
}
public UserInfo() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
答案 1 :(得分:0)
您应该探索hibernate验证器,它是用于bean验证的参考实现JSR-349。更多信息在这里https://jcp.org/en/jsr/detail?id=349。
hibernate验证器也是进行bean验证的行业标准(互联网上有很多可用的东西),并附带了许多流行的框架,如dropwizard等。它提供基于注释的验证,并允许您编写自己的基于自定义注释的验证
请参阅分步指南http://www.journaldev.com/2668/spring-validation-example-mvc-validator,其中作者将其与弹簧一起使用。