Filter HTML tags in forums and chat rooms

Source: Internet
Author: User
Tags html tags stringbuffer

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.