铁马冰河2000

导航

统计

String特殊字符工具类-StringEscapeUtil

============================================================================String特殊字符工具类:

复制代码
public class StringEscapeUtil {
    /**
     * HTML字符转义
     * @see 对输入参数中的敏感字符进行过滤替换,防止用户利用JavaScript等方式输入恶意代码
     * @see String input = <img src='http://t1.baidu.com/it/fm=0&gp=0.jpg'/>
     * @see HtmlUtils.htmlEscape(input);         //from spring.jar
     * @see StringEscapeUtils.escapeHtml(input); //from commons-lang.jar
     * @see 尽管Spring和Apache都提供了字符转义的方法,但Apache的StringEscapeUtils功能要更强大一些
     * @see StringEscapeUtils提供了对HTML,Java,JavaScript,SQL,XML等字符的转义和反转义
     * @see 但二者在转义HTML字符时,都不会对单引号和空格进行转义,而本方法则提供了对它们的转义
     * @return String 过滤后的字符串
     */
    public static String htmlEscape(String input) {
        if(StringCheckUtil.isEmpty(input)){
            return input;
        }
        input = input.replaceAll("&", "&amp;");
        input = input.replaceAll("<", "&lt;");
        input = input.replaceAll(">", "&gt;");
        input = input.replaceAll(" ", "&nbsp;");
        input = input.replaceAll("'", "&#39;");   //IE暂不支持单引号的实体名称,而支持单引号的实体编号,故单引号转义成实体编号,其它字符转义成实体名称
        input = input.replaceAll("\"", "&quot;"); //双引号也需要转义,所以加一个斜线对其进行转义
        input = input.replaceAll("\n", "<br/>");  //不能把\n的过滤放在前面,因为还要对<和>过滤,这样就会导致<br/>失效了
        return input;
    }
    
    public static String unHtmlEscape(String input) {
        if(StringCheckUtil.isEmpty(input)){
            return input;
        }
        input = input.replaceAll("&amp;", "&");
        input = input.replaceAll("&lt;", "<");
        input = input.replaceAll("&gt;", ">");
        input = input.replaceAll("&nbsp;", " ");
        input = input.replaceAll("&#39;", "'");   //IE暂不支持单引号的实体名称,而支持单引号的实体编号,故单引号转义成实体编号,其它字符转义成实体名称
        input = input.replaceAll("&quot;", "\""); //双引号也需要转义,所以加一个斜线对其进行转义
        input = input.replaceAll("<br/>", "\n");  //不能把\n的过滤放在前面,因为还要对<和>过滤,这样就会导致<br/>失效了
        return input;
    }
}
复制代码

 

============================================================================String特殊字符工具测试类:

复制代码
    /**
     * html转义
     */
    @Test
    public void test_htmlEscape() {
        String input = "<a href='index.html'>主页<a>";
        String htmlEscape = StringEscapeUtil.htmlEscape(input);
        System.out.println(htmlEscape);
        String unHtmlEscape = StringEscapeUtil.unHtmlEscape(htmlEscape);
        System.out.println(unHtmlEscape);
    }
复制代码

 

posted on   铁马冰河2000  阅读(1593)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示