1:注解
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface EmptyInterface {
String[] value();
}
2.:使用拦截器(没有使用处理器)
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.xinxing.annotation.EmptyInterface;
import com.xinxing.utils.StampToDate;
import net.coobird.thumbnailator.util.exif.IfdStructure;
/**
* 参数不能为空注解验证
* @author Administrator
*
*/
public class EmptyInterceptor implements Interceptor {
@Override
public void intercept(Invocation inv) {
EmptyInterface annotation = inv.getMethod().getAnnotation(EmptyInterface.class);
if (annotation != null) {
noEmpty(annotation, inv);
}
}
public void noEmpty(EmptyInterface annotation,Invocation inv) {
Controller con = inv.getController();
String header = con.getHeader("Content-Type"); //取出head头
if (header != null && header.indexOf("multipart/form-data") != -1) { //判断是否是form-data
String folderName = "loss/" + StampToDate.getMonthDay();
con.getFile("photo",folderName);
}
String[] value = annotation.value();
boolean isTrue = true;
String key = "";
for (String v : value) {
String parameter = con.getPara(v);
if (parameter == null || parameter.trim().length() == 0) {
isTrue = false;
key = v;
break;
}
}
if(isTrue){
inv.invoke();
}else{
con.setAttr("msg", key+"不能为空");
con.setAttr("code", "509");
con.renderJson();
}
}
}
3.在路由配置文件中添加addInterceptor(new EmptyInterceptor()); 一定放在最上面,第一个使用。
4,控制器方法使用注解@EmptyInterface({"areaName","longitude","latitude","distance"}) 或 @EmptyInterface(“id”),没有参数验证的请clear掉拦截器 或者 修改
if (annotation != null) {
noEmpty(annotation, inv);
}
让注解参数不为空再去判断 为空就往下执行
inv.invoke();