1、插件實現java
插件的功能就是加載校驗規則,實現代碼以下數據庫
package com.nmtx.plugins.validation; import java.util.Properties; import com.jfinal.core.Const; import com.jfinal.kit.Prop; import com.jfinal.kit.PropKit; import com.jfinal.plugin.IPlugin; public class ValidationPlugin implements IPlugin{ protected Prop prop = null; public ValidationPlugin(String fileName) { prop = PropKit.use(fileName, Const.DEFAULT_ENCODING); } public ValidationPlugin(String fileName, String encoding) { prop = PropKit.use(fileName, encoding); } /** * 初始化校驗規則 */ public boolean start() { Properties properties = prop.getProperties(); for (Object object : properties.keySet()) { String key = (String) object; String rule[] = properties.getProperty(key).split(","); ValidationRules.ruleMap.put(key, rule[0]); ValidationRules.ruleErrorMessageMap.put(key,rule[1]); } return true; } public boolean stop() { return true; } }
package com.nmtx.plugins.validation; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import com.jfinal.kit.StrKit; public class ValidationRules { static Map<String, String> ruleMap = new HashMap<String,String>(); static Map<String, String> ruleErrorMessageMap = new HashMap<String,String>(); public static boolean isMatch(String rule, String value) { boolean matchResult; if(rule.equals("required")){ matchResult = StrKit.notBlank(value); }else { if(StrKit.notBlank(value))matchResult = Pattern.compile(ruleMap.get(rule)).matcher(value).matches(); else matchResult = true; } return matchResult; } public static String getErrorMessage(String rule){ return ruleErrorMessageMap.get(rule); } }
規則加載後就是如何攔截校驗了,這裏用攔截器實現大概以下ide
package com.nmtx.plugins.validation; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import com.jfinal.aop.Duang; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.jfinal.kit.StrKit; import com.nmtx.common.ErrorCode; import com.nmtx.common.MessageResp; import com.nmtx.controller.para.IParaFormat; import com.nmtx.controller.para.impl.HumpToMiddleScoreFormat; public class ValidatorInterceptor implements Interceptor { private IParaFormat humpParaFormat = Duang.duang("humpParaFormat", HumpToMiddleScoreFormat.class); public void intercept(Invocation inv) { String methodName = inv.getMethodName(); Controller controller = inv.getController(); Method[] methods = controller.getClass().getDeclaredMethods(); boolean matchResult = true; for (Method method : methods) { if (method.getName().equals(methodName)) { boolean hasAnnotation = method.isAnnotationPresent(Validation.class); if (hasAnnotation) { Validation anno = method.getAnnotation(Validation.class); Map<String, String> ruleMap = dealRule(anno.rules()); for (String key : ruleMap.keySet()) { String value = controller.getPara(humpParaFormat.paraToFormat(key)); String rule = ruleMap.get(key); matchResult = ValidationRules.isMatch(rule, value); MessageResp<String> message = new MessageResp<String>(); message.setCode(ErrorCode.ERROR); if (!matchResult) { message.setMessage(humpParaFormat.paraToFormat(key)+ValidationRules.getErrorMessage(rule)); message.setData(""); controller.renderJson(message); break; } } } } } if (matchResult) inv.invoke(); } public Map<String, String> dealRule(String rules) { Map<String, String> map = new IdentityHashMap<String, String>(); if (StrKit.notBlank(rules)) { String[] paraRules = rules.split(";"); for (String paraRule : paraRules) { String[] para = paraRule.split("="); map.put(para[0], para[1]); } } return map; } }
有了攔截器,攔截的方法確定須要註解了,註解實現以下post
package com.nmtx.plugins.validation; import java.lang.annotation.*; /** * 定義Validator規則的註解 * @author lianghao * */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Validation { String rules (); }
這樣攔截插件構造就完成了ui
二,使用篇編碼
添加插件url
/** * 定義插件,如數據庫鏈接等一些插件 */ @Override public void configPlugin(Plugins me) { me.add(new ValidationPlugin("validation.properties")); }
添加全局攔截插件
/** * 必須按這種順序,不容許改,不得在新增新的全局攔截器 */ @Override public void configInterceptor(Interceptors me) { me.add(new ValidatorInterceptor()); }
只需一個註解就搞定參數校驗,demo以下code
@Validation(rules = "userName=required;password=required") public void login() { }
須要什麼規則還能夠本身加在配置文件裏,附上一些經常使用的校驗orm
email=^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$,"郵箱格式不正確" chinese=^[\u4e00-\u9fa5]+$,"不是中文" number=^[0-9]*$,"只能輸入數字" phone=^1+[0-9]{10}$,"號碼格式不正確" idcard=^(\\d{15}|\\d{18})$,"身份證號碼不正確"//15或18位 postCode=^[0-9]{6}$,"郵政編碼格式不正確" url=[a-zA-z]+://[^\s]*,"url格式不對" date=[0-9]{4}-[0-9]{2}-[0-9]{2},"時間格式不對(yyyy-mm-dd)" creditcard=^((?:4\d{3})|(?:5[1-5]\d{2})|(?:6011)|(?:3[68]\d{2})|(?:30[012345]\d),"信用卡格式不正確" acceptImg=[.](jpg|gif|bmp|png)$,"圖片後綴名格式不正確" acceptFile=[.](xls|xlsx|csv|txt)$,"文件後綴名格式不正確" required=required,"參數不能爲空"