在進行后端開發的過程當中,都會需要使用到字段非空判斷,請求的字段如果為空的話,則不走Controller。
本文記錄一下在JFinal當中配置自定義注解非空判斷。
首先 新建一個注解類
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();
}
創建自定義的Handler 繼承自JFinal的Handler
/**
* Created by Pencilso on 2017/5/4.
*/
public class HandlerInter extends Handler {
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
String urlPara[] = {null};
Action action = JFinal.me().getAction(target, urlPara);
EmptyInterface annotation = action.getMethod().getAnnotation(EmptyInterface.class);
if (annotation != null) {
noEmpty(annotation, target, request, response, isHandled);
} else next.handle(target, request, response, isHandled);
}
public void noEmpty(EmptyInterface annotation, String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
String header = request.getHeader("Content-Type"); //取出head頭
if (header != null && header.indexOf("multipart/form-data") != -1) { //判斷是否是form-data 否則有可能會報錯 之前線上出現過一次log信息
request = new MultipartRequest(request);
((MultipartRequest) request).getFiles();
}
String[] value = annotation.value();
for (String v : value) {
String parameter = request.getParameter(v);
if (parameter == null || parameter.trim().length() == 0) {
Utils.outEmpty(response, request, v);
isHandled[0] = true;
break;
}
}
if (!isHandled[0])
next.handle(target, request, response, isHandled);
}
}
新建一個Utils類
/**
*
* @param response 響應
* @param request 請求
* @param param 為空的字段
*/
public static void outEmpty(HttpServletResponse response, HttpServletRequest request, String param) {
try {
response.setHeader("Content-Type", "application/json;charset=UTF-8"); //設置返回頭是json格式
PrintWriter writer = response.getWriter();
request.getInputStream().close();
writer.println(ErrorInfo.Json(CodeUtils.ONERROR, param + " can 'not null").toString()); //輸出錯誤信息,我這里將其封裝了起來 封裝了一個JSON的數據
writer.flush();
writer.close();
} catch (Exception e) {
}
}
打開JFinal的Config類,在configHandler(Handlers me) 方法下 將自定義的Handler攔截器加入。
使用方法
單參使用可以直接 @EmptyInterface("field") 多參需要大括號擴起來。
為空測試
正常測試
起初本想通過攔截全局Controller來進行字段非空驗證,后來發現 一個Clear就將其給清除掉了。雖然Clear可以指定清除某一個攔截器,但不是很方便。
雖然官方也有Validator 配置,不過感覺不好使。