You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gym/SQLFilter.java

45 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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