java解决sql注入完整的工具类

java解决sql注入完整的工具类

工具类

package kl.gw.adc.cms.util;

import kl.gw.cloud.common.exception.ApiException;
import kl.gw.cloud.common.model.Condition;
import org.apache.commons.lang.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author sunrj
 */
public class RegexUtils {

    /**
     * 对Condition校验防止sql注入
     *
     * @param condition
     */
    public static void verifyCondition(Condition condition) {

        //filter校验
        Optional.ofNullable(condition.getFilter()).ifPresent(map -> map.forEach((key, value) -> {
            if (!key.contains("\"name\"")) {
                //校验key
                boolean rightfulKey = RegexUtils.isRightfulString(key);
                if (!rightfulKey) {
                    throw new ApiException(400, "filter参数中含有非法的列名:" + key);
                }
                //校验value
                for (String s : value) {
                    if (s.contains("'")) {
                        throw new ApiException(400, "filter参数中的值非法:" + value);
                    }
                }
            }
        }));

        //gte校验
        Optional.ofNullable(condition.getGte()).ifPresent(map -> map.forEach((key, value) -> {
            boolean rightfulkey = RegexUtils.isRightfulString(key);
            //校验key
            if (!rightfulkey) {
                throw new ApiException(400, "gte参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //lte校验
        Optional.ofNullable(condition.getLte()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "lte参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //gt校验
        Optional.ofNullable(condition.getGt()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "gt参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //lt校验
        Optional.ofNullable(condition.getLt()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "lt参数中含有非法的列名:" + key);
            }
            //校验value
            verifyTime(key,value);
        }));

        //page校验
        Optional.ofNullable(condition.getPage()).ifPresent(map -> map.forEach((key, value) -> {
            //校验key
            boolean rightfulKey = RegexUtils.isRightfulString(key);
            if (!rightfulKey) {
                throw new ApiException(400, "page参数中含有非法的列名:" + key);
            }
            //校验value
            boolean rightfulValue = RegexUtils.isRightfulString(String.valueOf(value));
            if (!rightfulValue) {
                throw new ApiException(400, "page参数中含有非法的值:" + value);
            }
        }));

        //sort校验
        Optional.ofNullable(condition.getSort()).ifPresent(map -> map.forEach((s) -> {
            boolean rightfulString = RegexUtils.isRightfulString(s);
            if (!rightfulString) {
                throw new ApiException(400, "sort参数中含有非法的列名:" + s);
            }
        }));

        //group校验
        Optional.ofNullable(condition.getGroup()).ifPresent(list -> list.forEach((s) -> {
            if (!s.contains("time(") && !s.contains("\"name\"")) {
                boolean rightfulString = RegexUtils.isRightfulString(s);
                if (!rightfulString) {
                    throw new ApiException(400, "group参数中含有非法的列名:" + s);
                }
            }
        }));
    }

    private static void verifyTime(String key, String value) {
        if ("time".equals(key)){
            boolean rightfulValue = RegexUtils.validDateStr(value, "");
            boolean rightfulValue2 = RegexUtils.validDateStr(value, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            //value不为yyyy-MM-dd'T'HH:mm:ss.SSS'Z'格式也不为yyyy-MM-dd HH:mm:ss时间格式时
            if (!rightfulValue && !rightfulValue2) {
                throw new ApiException(400, "参数的时间格式非法:" + value);
            }
        }else {
            boolean rightfulValue = RegexUtils.isRightfulString(value);
            if (!rightfulValue) {
                throw new ApiException(400, "参数中含有非法的列名:" + value);
            }
        }
    }

    /**
     * 判断是否为合法字符(a-zA-Z0-9-_)
     *
     * @param text
     * @return
     */
    public static boolean isRightfulString(String text) {
        return match(text, "^[A-Za-z0-9_-]+$");
    }

    /**
     * 正则表达式匹配
     *
     * @param text 待匹配的文本
     * @param reg  正则表达式
     * @return
     */
    private static boolean match(String text, String reg) {
        if (StringUtils.isBlank(text) || StringUtils.isBlank(reg)) {
            return false;
        }
        return Pattern.compile(reg).matcher(text).matches();
    }

    /**
     * 校验时间字符串是否合法
     *
     * @param dateStr the date str
     * @param pattern the pattern
     * @return the boolean
     */
    public static boolean validDateStr(String dateStr, String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            LocalDate.parse(dateStr, new DateTimeFormatterBuilder().appendPattern(pattern).parseStrict().toFormatter());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}


在需要校验的地方引用即可

@GetMapping
 @ApiOperation(value = "查询用户列表", notes = "查询用户列表")
 public ServerResponse<IPage<AccountManageVo>> queryAccount(Page<AccountManageVo> page) {
     //校验page中的字段,防止sql注入
  RegexUtils.verifyPageFileld(page);
  return ServerResponse.successMethod(accountManageService.queryAccount(page));
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 解析 SQL 替换数值的工具类通常可以用来将 SQL 语句中的参数值替换为具体的数值。下面是一个简单的实现: ```java public class SqlUtils { // 将 SQL 语句中的参数占位符替换为具体的数值 public static String replaceParams(String sql, Map<String, Object> params) { for (Map.Entry<String, Object> entry : params.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof Number) { sql = sql.replace(key, value.toString()); } else { sql = sql.replace(key, "'" + value.toString() + "'"); } } return sql; } public static void main(String[] args) { String sql = "SELECT * FROM table WHERE id = :id AND name = :name"; Map<String, Object> params = new HashMap<>(); params.put(":id", 1); params.put(":name", "John"); String replacedSql = replaceParams(sql, params); System.out.println(replacedSql); } } ``` 在上述代码中,`replaceParams` 方法接收一个 SQL 语句和一个参数 `Map`,循环遍历参数 `Map` 中的每个键值对,将 SQL 语句中的参数占位符替换为具体的数值。如果参数值是一个数字,直接使用 `toString()` 方法进行替换;如果参数值是一个字符串,需要在值的两侧添加单引号。 在 `main` 方法中,我们定义了一个 SQL 语句和一个参数 `Map`,调用 `replaceParams` 方法替换 SQL 语句中的参数,并打印替换后的 SQL 语句。 这样的工具类可以方便地用于拼接 SQL 语句,并将参数值替换为具体的数值,避免了直接拼接字符串导致的 SQL 注入的风险。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值