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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM