温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

模糊查询 防止 sql注入

发布时间:2020-07-25 19:45:12 来源:网络 阅读:1040 作者:zfeng111 栏目:数据库

mysql  mybatis 环境:

1>. 处理sql特殊字符 {"*","%","_"} --> 替换为 "/*","/%","/_"

2>.   sql 中处理,定义‘/’ 为转义字符  


public abstract class BaseEntity extends PrimaryKeyObject<Long> {

private static final long serialVersionUID = 1L;

@Transient // 用于注释pojo对象中的属性,被注释的属性将成为短暂的,不会持久化。

protected Boolean escapeChar;  // 是否包含转义字符

protected String keyword;   // 模糊查询关键字


public String getKeyword() {

return keyword == null ? null : keyword.trim();

}


public void setKeyword(String keyword) {

this.keyword = keyword == null ? null : keyword.trim();

}


public Boolean getEscapeChar() {

this.getNewKeyword();

return escapeChar;

}


public void setEscapeChar(Boolean escapeChar) {

this.escapeChar = escapeChar;

}


// 处理sql特殊字符 {"*","%","_"} --> 替换为 "/*","/%","/_"

private void getNewKeyword() {

if (escapeChar == null) {

escapeChar = false;

}

if (StringUtils.isNotEmpty(keyword) && !escapeChar) {

Pattern p1 = Pattern.compile("\\*|%|_");

Matcher m1 = p1.matcher(keyword);


StringBuffer buf = new StringBuffer();

while (m1.find()) {

m1.appendReplacement(buf, "/" + m1.group());

}

m1.appendTail(buf);

String newkeyword = buf.toString();


if (!keyword.equals(newkeyword)) {

this.setEscapeChar(true);

this.setKeyword(newkeyword);

}

}

}

}




<!-- 模糊查询 -->

<if test="keyword != null">

<choose>

<when test=true >

and (

name like CONCAT("%",#{keyword},"%") escape '/'

or 

uname like CONCAT("%",#{keyword},"%") escape '/'

)

</when>

<when test=false>

</when>

</choose>

</if>






向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI