Since forums and chat rooms are open systems, every user with permission can speak freely. But often there are some malicious users will use their openness to make trouble, such as in chat or in the forum when the article, embedded HTML tags, so that the system confusion. Therefore, if you want to write a robust forum or chat room, you must filter the HTML tags sent by the user.
Let's analyze how to filter these tags. As we all know, HTML tags are composed of two angle brackets "<", ">" and some of the statements, such as, as long as we receive the HTML statements in the "<", ">" corresponding to the < and "", in the send back on it. It's a lot clearer now. Now let's take a look at how this process is implemented in Java programs, and to save space, I only write the filtered function.
Public String htmlFilter(String inputString);
If(inputString.length()= =0 || inputString= = null)
{
return inputString;
}
///如果接收到的字符串为空值或者长度为零,则返回该字符串,
//因为空字符串是不可能*有<和>的
StringBuffer str=new StringBuffer(inputString.length()+6);
//创建空的缓冲区
char c=’’;
for(int i=0 ;i< inputString.length();i ++)
{
c= inputString.charAt(i);//逐个扫描输入的字符串,取下inputString中第i +1个字符
if (c= =’<’)
{
str.append(“<”);
}//如果c为‘<’,则在str缓冲中加入”<”代替‘<’
else if (c = =’>’)
{
str.append(“<”);
}//如果c为‘>’,则在str缓冲中加入”>”代替‘>’
else
{
str.append (c); //如果既无’<’ 也无’>’则直接把c中的值写入缓冲
}
}
return str.toString(); //返回滤过HTML标记的字符串
}
You see, the problem is solved by a simple Java function. You just add it to your forum or chat so that the program is on the line.