在进行后端开发的过程当中,都会需要使用到字段非空判断,请求的字段如果为空的话,则不走 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 配置,不过感觉不好使。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于