您的位置:首页 > Web前端 > JavaScript

jsp过滤输入框输入html特殊字符

2013-10-31 13:40 1401 查看
在html中的特殊字符输入之后,再次显示的时候,有可能会出现问题。如,在评论的时候输入:<script>alert(1);</script>在展示的时候,就会是弹框而不是显示这段话了。所以,在保存的时候,需要将html中的特殊字符进行过滤并且转换,显示的时候,自动会展示原来的样子。

代码HtmlCodeUtil

public class HtmlCodeUtil {
/// <summary>
/// 替换html中的特殊字符
/// </summary>
/// <param name="theString">需要进行替换的文本。</param>
/// <returns>替换完的文本。</returns>
public static String HtmlEncode(String theString)
{
theString = theString.replaceAll(">", ">");
theString = theString.replaceAll("<", "<");
theString = theString.replaceAll("  ", "  ");
theString = theString.replaceAll("  ", "  ");
theString = theString.replaceAll("\"", """);
theString = theString.replaceAll("\'", "'");
theString = theString.replaceAll("\n", "<br/> ");
return theString;
}

/// <summary>
/// 恢复html中的特殊字符
/// </summary>
/// <param name="theString">需要恢复的文本。</param>
/// <returns>恢复好的文本。</returns>
public static String HtmlDiscode(String theString)
{
theString = theString.replaceAll(">", ">");
theString = theString.replaceAll("<", "<");
theString = theString.replaceAll(" ", " ");
theString = theString.replaceAll("  ", "  ");
theString = theString.replaceAll(""", "\"");
theString = theString.replaceAll("'", "\'");
theString = theString.replaceAll("<br/> ", "\n");
return theString;
}

}


显示的时候,其实不用再转。直接就可以展示了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: