自定义参数注解参数校验
自定义注解
@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckParam {
/**
* 判断参数是否为null或“”,false不做校验,true校验(未校验trim())
*
* @return
*/
boolean check() default true;
}
参数校验工具类
public class CheckParamUtils {
/**
* 参数校验 {@link com.ruoyi.common.utils.checkParam.CheckParam}
*
* @param o
* @return
*/
public static boolean check(Object o) {
Class cla = o.getClass();
Field[] fields = cla.getDeclaredFields();
for (Field field : fields) {
CheckParam checkParam = field.getAnnotation(CheckParam.class);
if (checkParam == null) {
continue;
}
if (checkParam.check()) {
try {
field.setAccessible(true);
Object obj = field.get(o);
if (obj == null || obj == "") {
System.out.println("参数校验失败,失败参数:" + field.getName());
return false;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
System.out.println("参数校验异常,失败参数:" + field.getName());
}
}
}
return true;
}
}
实体类
@Data
@ApiModel
public class AddOrderVO implements Serializable {
@CheckParam
@ApiModelProperty("车辆信息")
private String carname;
@CheckParam
@ApiModelProperty("租期")
private Integer leasetime;
@CheckParam
@ApiModelProperty("押金")
private BigDecimal deposit;
@CheckParam
@ApiModelProperty("月租金")
private BigDecimal monthlyrent;
@CheckParam
@ApiModelProperty("承租人姓名")
private String rentername;
@CheckParam
@ApiModelProperty("承租人身份证号")
private String renteridcard;
@CheckParam
@ApiModelProperty("承租人手机号")
private String renteridphone;
}
调用参数校验
@ApiOperation("新增司机端求租发布")
@PostMapping("/addUserWanted")
@BeahviorIntercept(event = "hire_issue", paramsOpen = false, personage = BeahviorIntercept.BeahviorRecordState.peosonal)
public ApiResult<Object> addUserWanted(@RequestBody AddUserWantedVO addUserWnatedVO) {
if (!CheckParamUtils.check(addUserWnatedVO)) {
return ApiResult.fail("参数校验失败");
}
driverMessageService.addUserWanted(addUserWnatedVO.change(WebUtil.getUserId()));
return ApiResult.ok();
}