在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;
}
}
显示的时候,其实不用再转。直接就可以展示了