SqlUtil.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.ruoyi.common.utils.sql;
  2. import com.ruoyi.common.exception.UtilException;
  3. import com.ruoyi.common.utils.StringUtils;
  4. /**
  5. * sql操作工具类
  6. *
  7. * @author ruoyi
  8. */
  9. public class SqlUtil
  10. {
  11. /**
  12. * 定义常用的 sql关键字
  13. */
  14. public static String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
  15. /**
  16. * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
  17. */
  18. public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
  19. /**
  20. * 检查字符,防止注入绕过
  21. */
  22. public static String escapeOrderBySql(String value)
  23. {
  24. if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
  25. {
  26. throw new UtilException("参数不符合规范,不能进行查询");
  27. }
  28. return value;
  29. }
  30. /**
  31. * 验证 order by 语法是否符合规范
  32. */
  33. public static boolean isValidOrderBySql(String value)
  34. {
  35. return value.matches(SQL_PATTERN);
  36. }
  37. /**
  38. * SQL关键字检查
  39. */
  40. public static void filterKeyword(String value)
  41. {
  42. if (StringUtils.isEmpty(value))
  43. {
  44. return;
  45. }
  46. String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
  47. for (String sqlKeyword : sqlKeywords) {
  48. if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
  49. throw new UtilException("参数存在SQL注入风险");
  50. }
  51. }
  52. }
  53. }