很多小伙伴在做网站的时候可能会遇到一些敏感词汇不能出现在网站,但是又不能控制用户的输入,所以贴出一个关键字过滤功以解忧愁
1、前端使用ajax提交表单,将要过滤的字段提交到后台过滤
function audit(obj){//保存并过滤关键字
var a = obj;
document.getElementById("checked").value = a;
$.ajax({//将内容提交到后台过滤关键字
type:"POST",
dataType:"JSON",
url:"cmsContentFiltration/filtration.do",//过滤接口我的是这样的
data:$('#form').serialize(),//将表单序列化提交后台过滤关键字
success:function(str){//回调函数中进行是否保存操作
if(str.data==""|| str.data===undefined){//无敏感词汇直接保存
$("#form").submit()
}else{
if(window.confirm('所提交的内容包含:'+str.data+'等以下敏感词汇,是否保存?')){
$("#form").submit();
return true;
}else{
return false;
}
}
}
});
}
2、控制层
/** * @ClassName filtration * @Description * @Author shenWB * @Date 2019/6/27 10:12 * @Version 1.0 **/ @RequestMapping("filtration") @ResponseBody public Object filtration(CmsContent entity, CmsContentAttribute attribute, @ModelAttribute CmsContentParamters contentParamters, Boolean draft, Boolean checked, HttpServletRequest request, HttpSession session, ModelMap model){ Map<String, Object> m = new HashMap<String, Object>(); List<String> str =new ArrayList<String>();//要过滤字段的集合 str.add(entity.getTitle());//标题 //if (!attribute.getText().equals(null)) { if (attribute != null && attribute.getText() != null && !attribute.getText().isEmpty()) { str.add(attribute.getText());//正文 } //if (!entity.getEditor().equals(null)) { if (entity != null && entity.getEditor()!=null && !entity.getEditor().isEmpty()) { str.add(entity.getEditor());//编辑 } //if (!entity.getDescription().equals(null)) { if (entity != null && entity.getDescription() != null && !entity.getDescription().isEmpty()) { str.add(entity.getDescription());//描述 } if(contentParamters.getCategoryExtendDataList()!=null){ for (ExtendData obj : contentParamters.getCategoryExtendDataList()) {//扩展字段 str.add(obj.getValue()); } } SensitivewordFilter filter = new SensitivewordFilter();//过滤词工具类对象 String sb="";//拼接字符串,用于前台提示用户具体包含哪些关键字, for (String string : str) {//要过滤字段的集合,取出逐一过滤 Set<String> set = filter.getSensitiveWord(string, 1);//要过滤的字段传到工具类中去过滤 if(!set.toString().equals("[]")){