JFinal 参数校验插件扩展,让后台参数校验像js一样方式好用

简介: 一、插件实现 插件的功能就是加载校验规则,实现代码如下 package com.nmtx.plugins.validation; import java.util.Properties; import com.

一、插件实现

插件的功能就是加载校验规则,实现代码如下

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);
    }
}

规则加载后就是如何拦截校验了,这里用拦截器实现大概如下

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;
    }

}

有了拦截器,拦截的方法肯定需要注解了,注解实现如下

package com.nmtx.plugins.validation;

import java.lang.annotation.*;

/**
 * 定义Validator规则的注解
 * @author lianghao
 *
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Validation {
    String rules ();
}

这样拦截插件构造就完成了

二,使用篇

添加插件

    /**
     * 定义插件,如数据库连接等一些插件
     */
    @Override
    public void configPlugin(Plugins me) {
     
        me.add(new ValidationPlugin("validation.properties"));
         
     
    }

添加全局拦截

/**
     * 必须按这种顺序,不允许改,不得在新增新的全局拦截器
     */
    @Override
    public void configInterceptor(Interceptors me) {
        me.add(new ValidatorInterceptor());
    }

只需一个注解就搞定参数校验,demo如下

    
    @Validation(rules = "userName=required;password=required")
    public void login() {
        
    }

需要什么规则还可以自己加在配置文件里,附上一些常用的校验

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,"参数不能为空"

相关文章
|
24天前
|
移动开发 JavaScript 前端开发
JavaScript的正则表达式实现邮箱校验
JavaScript的正则表达式实现邮箱校验
43 1
|
1月前
egg.js 24.18参数验证
egg.js 24.18参数验证
28 0
egg.js 24.18参数验证
|
2月前
|
JavaScript 前端开发 安全
使用 Node.js 插件给指定目录下的所有图片添加上文字水印
使用 Node.js 插件给指定目录下的所有图片添加上文字水印
53 0
|
2月前
|
JavaScript 前端开发
Google Earth Engine(GEE)扩展——ee-polyfill JavaScript 方法 (ES6+)
Google Earth Engine(GEE)扩展——ee-polyfill JavaScript 方法 (ES6+)
16 1
|
3月前
|
人工智能 JavaScript 前端开发
【利用AI让知识体系化】TypeScript目标:扩展JavaScript能力(二)
【利用AI让知识体系化】TypeScript目标:扩展JavaScript能力
|
3月前
|
人工智能 JavaScript 前端开发
【利用AI让知识体系化】TypeScript目标:扩展JavaScript能力(一)
【利用AI让知识体系化】TypeScript目标:扩展JavaScript能力
|
1月前
|
存储 JavaScript 前端开发
在JavaScript中,对象和数组是如何进行扩展的?
在JavaScript中,对象和数组是如何进行扩展的?
20 4
|
1月前
|
JavaScript 前端开发 API
js截取图片地址后面的参数和在路径中截取文件名或后缀名
在处理网页上的图片资源或者其他类型的文件资源时,你可能会遇到需要使用这些技巧的情况。以下是一些具体的使用场景:
11 0
|
7天前
|
JavaScript
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
|
12天前
|
JavaScript 前端开发
为 setTimeout 或 setInterval 提供一个字符串作为第一个参数(js的问题)
为 setTimeout 或 setInterval 提供一个字符串作为第一个参数(js的问题)