diff --git a/SQLFilter.java b/SQLFilter.java new file mode 100644 index 0000000..78ce28e --- /dev/null +++ b/SQLFilter.java @@ -0,0 +1,45 @@ +package com.utils; + +// 导入Apache Commons Lang3工具类库 +import org.apache.commons.lang3.StringUtils; +// 导入自定义异常类 +import com.entity.EIException; + +// 定义SQL过滤工具类 +public class SQLFilter { + + // SQL注入过滤方法,对输入字符串进行安全处理 + public static String sqlInject(String str) { + // 检查输入字符串是否为null或空字符串 + if (StringUtils.isBlank(str)) { + // 如果是空字符串则返回null + return null; + } + // 替换字符串中的单引号为空字符串 + str = StringUtils.replace(str, "'", ""); + // 替换字符串中的双引号为空字符串 + str = StringUtils.replace(str, "\"", ""); + // 替换字符串中的分号为空字符串 + str = StringUtils.replace(str, ";", ""); + // 替换字符串中的反斜杠为空字符串 + str = StringUtils.replace(str, "\\", ""); + + // 将处理后的字符串转换为小写,便于统一检查 + str = str.toLowerCase(); + + // 定义SQL关键字黑名单数组 + String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; + + // 遍历关键字黑名单数组 + for (String keyword : keywords) { + // 检查处理后的字符串是否包含当前关键字 + if (str.indexOf(keyword) != -1) { + // 如果包含则抛出非法字符异常 + throw new EIException("包含非法字符"); + } + } + + // 返回经过安全处理的字符串 + return str; + } +} \ No newline at end of file