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

在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;
    }
    
}

显示的时候,其实不用再转。直接就可以展示了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值