最近在写个app玩,其中有个发帖功能,服务器端模块infomationControl的postInfo方法负责写入用户提交的信息。代码:
private void postInfo(Object fromWho, TLMsg msg) {
String userid = getUserid();
TLMsg infomsg=createMsg().setAction("postInformation").addArgs(msg.getArgs());
infomsg.setParam("userid",userid);
int catid = Integer.parseInt((String)msg.getParam("catid"));
int areaid = Integer.parseInt((String)msg.getParam("areaid"));
int info_type = Integer.parseInt((String)msg.getParam("info_type"));
infomsg.setParam("catid",catid);
infomsg.setParam("areaid",areaid);
infomsg.setParam("info_type",info_type);
HttpServletRequest request =(HttpServletRequest)getModuleInFactory("servletRequest");
String userip =request.getRemoteAddr();
infomsg.setParam("ip",userip);
infomsg.setParam("stream_times",10);
TLMsg returnMsg= putMsg("informationModule", infomsg);
HashMap<String, Object> result =new HashMap<>();
putToClient("0000","publish ok ");
}
功能很简单,将用户提交的内容后写入数据库,其中msg里是用户提交的内容,由前期模块自动取来。写完后过了几天想起个严重问题——中国的互联网特色,内容要过滤敏感词啊,上面的代码中用户提交的内容没有前期处理和过滤。如果在方法中增加敏感词过滤代码,但如果以后不需要过滤或者增加其他的过滤那怎么办,例如验证用户输入,还要改代码?太麻烦了,另外也不符合逻辑,写数据就是写数据的,不应该放其他东西。通过消息编这将很简单实现,在方法的前期消息处理中增加过滤消息就行了。在infomationControl的配置中,增加消息执行前处理消息列表:
<beforeMsgTable>
<action value="postInfo" >
<msg msgid="filter_postInfo" destination="userInPutFilter"
useInputMsg="false" usePreReturnMsg ="false" />
</action>
</beforeMsgTable>
配置的意思是在执行postInfo方法前,执行消息 filter_postInfo,消息目的是userInPutFilter 模块,在userInPutFilter的模块配置中定义消息链filter_postInfo:
<msgid value="filter_postInfo" >
<msg action="checkString" useInputMsg="false" usePreReturnMsg ="false"
checkVarList="content;title" content="10;500" title="0;0" />
<msg action="checkBadWord" useInputMsg="false" usePreReturnMsg ="false" />
</msgid>
对于消息链filter_postInfo ,依次执行 checkString 和checkBadWord 方法,checkBadWord为过滤敏感词方法。在userInPutFilte定义过滤方法:
private TLMsg checkBadWord(Object fromWho, TLMsg msg) {
TLMsg dmsg =(TLMsg) msg.getParam(DOWITHMAG);
String content = (String) dmsg.getParam("content");
if(badWordUtil2.isContaintBadWord(content, 2))
{
putFilterMsg("1100","包含非法字符" ,null);
return createMsg().setParam(DONEXTMSG,"false");
}
else
return null ;
}
protected void putFilterMsg(String code ,String message ,HashMap<String ,Object> serverResult){
outData odata = creatOutDataMsg();
odata.addData("code",code);
odata.addData("message",message);
odata.addData("result",serverResult);
putOutData(odata);
}
如果包含敏感词,则不执行下个消息 ,返回用户提示。这样在遵守逻辑不更改源代码的基础上,灵活、方便的对功能进行了扩充。如果还需要其他过滤,则在过滤消息链中增加项目即可,如果不在需要过滤,则取消配置项即可。太方便了!