How to escape HTML special characters in Java?

后端 未结 5 1654
名媛妹妹
名媛妹妹 2021-01-01 21:01

Is there a way to convert a string to a string that will display properly in a web document? For example, changing the string

\"\"
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 21:25

    Better do it yourself, if you know the logic behind - it is easy:

     public class ConvertToHTMLcode {
            public static void main(String[] args) throws IOException {
              String specialSymbols = "ễ%ß Straße";
              System.out.println(convertToHTMLCodes(specialSymbols)); //ễ%ß
       }
    
       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();
       }
    }
    

提交回复
热议问题