Java物件校驗框架之Oval
編寫登入 註冊等功能的時候後臺經行校驗,可以使用oval框架,簡單實用
package com.meadin.main.request;
import com.meadin.module.base.BaseRequest;
import net.sf.oval.constraint.Length;
import net.sf.oval.constraint.NotEmpty;
import net.sf.oval.constraint.NotNull;
public class VisitorRequest extends BaseRequest {
@NotNull
@NotEmpty
private String contacts;
@NotNull
@NotEmpty
@Length(min = 11, max = 11)//電話號碼長度的驗證
private String phone;
@NotNull
@NotEmpty
private String company;
@NotNull
@NotEmpty
private String duty;
@NotNull
@NotEmpty
private long systemCode;
@NotNull
@NotEmpty
@Length( max = 100)
private String remak;
public String getContacts() {
return contacts;
}
public void setContacts(String contacts) {
this.contacts = contacts == null ? null : contacts.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company == null ? null : company.trim();
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty == null ? null : duty.trim();
}
public long getSystemCode() {
return systemCode;
}
public void setSystemCode(long systemCode) {
this.systemCode = systemCode;
}
public String getRemak() {
return remak;
}
public void setRemak(String remak) {
this.remak = remak == null ? null : remak.trim();
}
}
校驗的程式碼
@RequestMapping(value = "/")
@ResponseBody
public Object submit(VisitorRequest visitor, String callback) throws Exception {
// 對傳入的物件經行驗證
Validator validator = new Validator();
List<ConstraintViolation> list = validator.validate(visitor);
//只要返回集合中有元素就說明有不合法的引數
if (list.size() > 0) {
String result = callback + "(" + JSONObject.toJSON(ApiResult.build(0, "引數錯誤!!!")).toString() + ");";
return result;
}
}