您好,登錄后才能下訂單哦!
前言
前幾天學習了反射和自定義注解,剛好工作中遇到一個小問題:前臺傳遞到后臺的必填字段為空,導致不能插入數據庫。就是這樣一個小問題,讓我考慮到是否可以做一個通用的方法,讓前臺傳遞過來的必填字段在后臺也校驗一遍,如果傳遞為空,則把響應字段返回提示。因此,我考慮的是用注解的方式,在必填字段上面定義,利用反射得到必填字段的字段名,判斷是否為空,并返回響應的信息。
需求模擬
假設客戶有:姓名,年齡,地址,手機號碼,身份證號等信息,而我們是做金融業務,所以關鍵是看客戶的三要素:姓名,身份證號,手機號碼。我們要保證前臺傳遞過來的這三個值不為空。
廢話不多說,直接上代碼。只看紅框里面的即可。
目錄結構
客戶信息類:Customer
這個是個實體類,我們在:姓名,身份證號碼,手機號碼上都用了我們的自定義注解。
package com.dao.chu.po; /** * * <p>Title: Customer</p> * <p>Description:客戶信息實體 </p> */ public class Customer { private int id; @IsRequired private String name; // 姓名 @IsRequired private String idnum; // 身份證號碼 @IsRequired private String phone; // 手機號 private String sex; // 性別 private int age; // 年齡 private String address; // 地址 @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", idnum=" + idnum + ", phone=" + phone + ", sex=" + sex + ", age=" + age + ", address=" + address + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdnum() { return idnum; } public void setIdnum(String idnum) { this.idnum = idnum; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
自定義注解類:IsRequired
package com.dao.chu.po; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * <p>Title: IsRequired</p> * <p>Description: 字段是否必填 </p> */ @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.FIELD}) public @interface IsRequired { /** * * <p>Title: isRequired</p> * <p>Description:true:必填 false:非必填 </p> * @return */ boolean isRequired() default true; }
關鍵工具類:PoUtils
我們在這個類里面主要用了反射的知識,得到帶有自定義注解的字段,并取得這個對象的值進行判斷
package com.dao.chu.po; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import javax.jws.WebResult; import com.sun.xml.internal.ws.util.StringUtils; /** * * <p>Title: PoUtils</p> * <p>Description:Po操作工具類 </p> */ @SuppressWarnings("unused") public class PoUtils { /** * <p>Title: getProperties</p> * <p>Description: 獲取javabean屬性通用方法 </p> * @param t * @param beanName * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws IntrospectionException */ private static <T> Object getProperties(T t, String beanName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException { Object nameValue = new PropertyDescriptor(beanName, t.getClass()).getReadMethod().invoke(t); return nameValue; } /** * <p>Title: IsFieldBlank</p> * <p>Description:判斷前臺傳過來的必填字段是否為空 ,不正確則將相應字段返回 </p> * @param t * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws IntrospectionException */ public static <T> RespBody IsFieldBlank(T t) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException { RespBody respBody = new RespBody(); StringBuffer sb = new StringBuffer(); Field[] declaredFields = t.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); String name = field.getName(); boolean fieldHasAnno = field.isAnnotationPresent(IsRequired.class); if (fieldHasAnno) { IsRequired annotation = field.getAnnotation(IsRequired.class); boolean required = annotation.isRequired(); if (required) { Object value = getProperties(t, name); if (null == value) { sb.append(name + ","); } } } } if (null==sb.toString()||"".equals(sb.toString())) { respBody.isSuccess(); } respBody.setSuccess(false); respBody.setMsg(sb.toString().substring(0,sb.toString().lastIndexOf(",")) + " is required"); return respBody; } }
RespBody:響應實體類
封裝了響應的成功失敗以及一些信息
package com.dao.chu.po; /** * * <p>Title: RespBody</p> * <p>Description: 響應實體類</p> */ public class RespBody { private boolean isSuccess = true; private String msg; private Object data; public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public RespBody(boolean isSuccess, String msg, Object data) { super(); this.isSuccess = isSuccess; this.msg = msg; this.data = data; } public RespBody(boolean isSuccess, String msg) { super(); this.isSuccess = isSuccess; this.msg = msg; } public RespBody() { } @Override public String toString() { return "ReturnBody [isSuccess=" + isSuccess + ", msg=" + msg + ", data=" + data + "]"; } }
測試類:IsRequiredTest
package com.dao.chu.po; /** * * <p>Title: IsRequiredTest</p> * <p>Description: 必填成員變量測試類</p> */ public class IsRequiredTest { public static void main(String[] args) { Customer customer = new Customer(); try { //=========第一次不賦值========== RespBody respBody = PoUtils.IsFieldBlank(customer); //不通過則返回提示信息 if (!respBody.isSuccess()) { System.out.println("1."+respBody.getMsg()); } //=========第二次給姓名賦值========== customer.setName("張三"); respBody = PoUtils.IsFieldBlank(customer); //不通過則返回提示信息 if (!respBody.isSuccess()) { System.out.println("2."+respBody.getMsg()); } } catch (Exception e) { e.printStackTrace(); } } }
輸出結果
第一次三個值都為空,提示三個都是必填的,第二次因為姓名賦值了,所以提示另外兩個是必填的,本次實驗宣告結束,本人知識有限,若有更好的方法歡迎指正
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。