直接上代码
1.添加依赖 <dependency><groupId>com.github.houbb</groupId><artifactId>sensitive-word</artifactId><version>0.25.0</version> </dependency>
2.自定义配置类
import cn.mftcc.cus.common.constant.ZQWordDeny;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.github.houbb.sensitive.word.support.deny.WordDenys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Auther: zhaoying
* @Date: 2025-12-25 11:27
* 敏感词处理
*/
@Configuration
public class ZQSensitiveWordBs {
@Autowired
private ZQWordDeny zqWordDeny;
@Bean
public SensitiveWordBs sensitiveWordBsSet() {
SensitiveWordBs init = SensitiveWordBs.newInstance().
wordDeny(WordDenys.chains(zqWordDeny))
.ignoreCase(true)
.ignoreWidth(true)
.ignoreNumStyle(true)
.ignoreChineseStyle(true)
.ignoreEnglishStyle(true)
.ignoreRepeat(true)
.init();
return init;
}
}
各项配置的说明如下:
| 序号 | 方法 | 说明 |
|---|---|---|
| 1 | ignoreCase | 忽略大小写 |
| 2 | ignoreWidth | 忽略半角圆角 |
| 3 | ignoreNumStyle | 忽略数字的写法 |
| 4 | ignoreChineseStyle | 忽略中文的书写格式 |
| 5 | ignoreEnglishStyle | 忽略英文的书写格式 |
| 6 | ignoreRepeat | 忽略重复词 |
| 7 | enableNumCheck | 是否启用数字检测。默认连续 8 位数字认为是敏感词 |
| 8 | enableEmailCheck | 是有启用邮箱检测 |
| 9 | enableUrlCheck | 是否启用链接检测 |
3.直接在代码中使用
public void insert(TestEntity testEntity) throws ServiceException {
try{
/**
* 敏感词筛查
*/
if(SensitiveWordHelper.contains(testEntity.getWorkUnit())){
cusCustomerEntity.setWorkUnit(null);
throw new ServiceException("ERROR_CODE","命中敏感词库,请重新输入");
}
cusCustomerMapper.insert(cusCustomerEntity);
}catch (Exception e){
throw new ServiceException(SysConstant.MSG_CONFIG_SAVE_ERROR,"新增失败",e);
}
}
部分api使用方法的介绍
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| contains(String) | 待验证的字符串 | 布尔值 | 验证字符串是否包含敏感词 |
| replace(String, ISensitiveWordReplace) | 使用指定的替换策略替换敏感词 | 字符串 | 返回脱敏后的字符串 |
| replace(String, char) | 使用指定的 char 替换敏感词 | 字符串 | 返回脱敏后的字符串 |
| replace(String) | 使用 * 替换敏感词 | 字符串 | 返回脱敏后的字符串 |
| findAll(String) | 待验证的字符串 | 字符串列表 | 返回字符串中所有敏感词 |
| findFirst(String) | 待验证的字符串 | 字符串 | 返回字符串中第一个敏感词 |
| findAll(String, IWordResultHandler) | IWordResultHandler 结果处理类 | 字符串列表 | 返回字符串中所有敏感词 |
| findFirst(String, IWordResultHandler) | IWordResultHandler 结果处理类 | 字符串 | 返回字符串中第一个敏感词 |