这里面需要用到Pattern和matcher两个类中提供的方法,代码如下:
public boolean containsSensitiveWords(String content) {
logger.info("The method containsSensitiveWords check start:");
logger.info("The content:" + content);
boolean result = false;
// 取得所有敏感词
//String sensitiveWords = redisClient.get(RedisConstants.ZR_SENSITIVE_WORDS);
String sensitiveWords=null;
if(StringUtils.isEmpty(sensitiveWords)){
// 如果未取到,从数据库读取
sensitiveWords = getAllSensitiveWordsFromDB();
}
//logger.info("The all:" + sensitiveWords);
// 如果取到了设置的敏感词,执行校验
if(!StringUtil.isNullOrBlank(sensitiveWords)){
Pattern pattern = Pattern.compile(sensitiveWords);
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
result = true;
}
}
logger.info("The result:" + result);
return result;
}
从数据库中获取所有的敏感词(敏感词自己定义),如下:
/**
* 功能描述: 从数据库中取得所有的敏感词,组织表达式返回
*/
private String getAllSensitiveWordsFromDB(){
StringBuffer buf = new StringBuffer();
// 查询数据库,取得全部敏感词集合
List<SensitiveWord> wordList =
wordDao.queryForList("productReview.getAllSensitiveWords",
null, SensitiveWord.class);
if(!wordList.isEmpty()){
for(int i=0; i<wordList.size(); i++){
buf.append(wordList.get(i).getWord());
if(i != wordList.size()-1){
buf.append("|");
}
}
}
return buf.toString();
}
从数据库中取敏感词的sql语句:
<!-- 获取所有敏感词 -->
<sql id="getAllSensitiveWords">
<![CDATA[
SELECT WORD FROM SENSITIVE_WORD
WITH UR
]]>
</sql>