关键词过滤
Mongo-Plus 提供了关键词过滤功能,旨在防止用户存入违规敏感词,使开发更简单。从2.1.9版本开始,Mongo-Plus 支持通过注解或全局方式进行过滤关键词。
说明
Mongo-Plus检测到敏感词后,将会抛出SensitiveWordException异常,可通过捕获该异常,获取到敏感词内容,暂不支持替换
依赖引入
通过引入mongo-plus-sensitive-word来实现关键词的自动过滤
xml
<dependencyManagement>
<dependencies>
<!-- mongoplus-bom -->
<dependency>
<groupId>com.mongoplus</groupId>
<artifactId>mongo-plus-bom</artifactId>
<version>最新版本</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- mongoplus关键词依赖 -->
<dependency>
<groupId>com.mongoplus</groupId>
<artifactId>mongo-plus-sensitive-word</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
配置
mongoplus支持两种过滤方式,分别是局部和全局,局部过滤需要通过使用 @SensitiveWord 标注;全局则无需使用,需要注意的是,全局过滤效率将会大打折扣,谨慎使用
yaml
mongo-plus:
sensitive-word:
# 敏感词校验类型,默认局部
sensitive-type: LOCAL
# 是否忽略大小写
ignore-case: true
# 是否忽略全角、半角
ignore-width: true
# 是否忽略数字样式
ignore-num-style: true
# 是否忽略中文样式
ignore-chinese-style: true
# 是否忽略英文样式
ignore-english-style: true
# 是否忽略重复字符
ignore-repeat: false
# 是否忽略特殊字符
ignore-char: false
# 启用连续数字检测
enable-num-check: false
# 启用邮箱检测
enable-email-check: false
# 启用 URL 检测
enable-url-check: false
# 启用 IPv4 检测
enable-ipv4-check: false
示例
使用局部校验类型,需要使用@SensitiveWord注解,只可标注在实体类的字段上
java
@CollectionName("user")
public class User{
//设置字段过滤敏感词
@SensitiveWord
private String userName;
}
加载敏感词
MongoPlus提供了动态加载、卸载敏感词的接口,可以加载自定义敏感词
java
// 注册为Bean
@Component
public class CustomLoadExtraWord implements LoadExtraWord {
@Override
public List<String> deny() {
return List.of("拒绝出现的数据-返回的内容被当做是敏感词");
}
@Override
public List<String> allow() {
return List.of("允许的内容-返回的内容不被当做敏感词");
}
}
动态加载
MongoPlus提供了动态加载敏感词黑白名单的功能,可在项目运行时新增、删除
java
// 注入SensitiveWordManager
@Resource
private SensitiveWordManager sensitiveWordManager;
// 黑名单
/** ==================添加================== */
/**
* 添加敏感词
* @param words 敏感词
*/
void addWordBlacklist(String... words);
/**
* 添加敏感词
* @param words 敏感词
*/
void addWordBlacklist(Collection:String words);
/**
* 添加敏感词
* @param wordFile 敏感词文件路径
*/
void addWordBlackList(Path wordFile);
/** ==================删除================== */
/**
* 删除敏感词
* @param words 敏感词
*/
void removeSensitiveWord(String... words);
/**
* 删除敏感词
* @param words 敏感词
*/
void removeSensitiveWord(Collection:String words);
/**
* 删除敏感词
* @param wordFile 敏感词文件路径
*/
void removeSensitiveWord(Path wordFile);
// 白名单
/** ==================添加================== */
/**
* 添加敏感词白名单
* @param words 敏感词
*/
void addSensitiveWordAllow(String... words);
/**
* 添加敏感词白名单
* @param words 敏感词
*/
void addSensitiveWordAllow(Collection<String> words);
/**
* 添加敏感词白名单
* @param wordFile 敏感词文件路径
*/
void addSensitiveWordAllow(Path wordFile);
/** ==================删除================== */
/**
* 删除敏感词白名单
* @param words 敏感词
*/
void removeSensitiveWordAllow(String... words);
/**
* 删除敏感词白名单
* @param words 敏感词
*/
void removeSensitiveWordAllow(Collection<String> words);
/**
* 删除敏感词白名单
* @param wordFile 敏感词文件路径
*/
void removeSensitiveWordAllow(Path wordFile);