如何在Java中转义HTML特殊字符?

问题描述 投票:15回答:5

有没有办法将字符串转换为可在Web文档中正确显示的字符串?例如,更改字符串

"<Hello>"

"&lt;Hello&gt;"
java html
5个回答

3
投票

这通常被称为“HTML转义”。我不知道标准库中有什么用于执行此操作(尽管您可以通过使用XML转义来近似它)。但是,有很多第三方库可以做到这一点。来自org.apache.commons.lang的StringEscapeUtils有一个可以做到这一点的escapeHtml方法。


2
投票
public static String stringToHTMLString(String string) {
    StringBuffer sb = new StringBuffer(string.length());
    // true if last char was blank
    boolean lastWasBlankChar = false;
    int len = string.length();
    char c;

    for (int i = 0; i < len; i++)
        {
        c = string.charAt(i);
        if (c == ' ') {
            // blank gets extra work,
            // this solves the problem you get if you replace all
            // blanks with &nbsp;, if you do that you loss 
            // word breaking
            if (lastWasBlankChar) {
                lastWasBlankChar = false;
                sb.append("&nbsp;");
                }
            else {
                lastWasBlankChar = true;
                sb.append(' ');
                }
            }
        else {
            lastWasBlankChar = false;
            //
            // HTML Special Chars
            if (c == '"')
                sb.append("&quot;");
            else if (c == '&')
                sb.append("&amp;");
            else if (c == '<')
                sb.append("&lt;");
            else if (c == '>')
                sb.append("&gt;");
            else if (c == '\n')
                // Handle Newline
                sb.append("&lt;br/&gt;");
            else {
                int ci = 0xffff & c;
                if (ci < 160 )
                    // nothing special only 7 Bit
                    sb.append(c);
                else {
                    // Not 7 Bit use the unicode system
                    sb.append("&#");
                    sb.append(new Integer(ci).toString());
                    sb.append(';');
                    }
                }
            }
        }
    return sb.toString();
}

1
投票

HTMLEntities是一个开源Java类,包含一组静态方法(htmlentities,unhtmlentities,...),用于将特殊字符和扩展字符转换为HTML权限,反之亦然。

http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities


0
投票

如果您了解背后的逻辑,那么最好自己动手做 - 这很简单:

 public class ConvertToHTMLcode {
        public static void main(String[] args) throws IOException {
          String specialSymbols = "ễ%ß Straße";
          System.out.println(convertToHTMLCodes(specialSymbols)); //&#7877;%&#223;
   }

   public static String convertToHTMLCodes(String str) throws IOException {
      StringBuilder sb = new StringBuilder();
      int len = str.length();
      for(int i = 0; i < len; ++i) {
          char c = str.charAt(i);
         if (c > 127) {
            sb.append("&#");
            sb.append(Integer.toString(c, 10));
            sb.append(";");
        } else {
            sb.append(c);
        }
     }
       return sb.toString();
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.