Html call in java?

Is there a standard class in Java that has a method for HTML-escape strings?

< ... &lt;
> ... &gt;
+3
source share
3 answers

No no. You can use Apache Commons Lang StringEscapeUtils#escapeHtml4 for this.


Refresh . If you have an aversion to third-party libraries and / or a preference for homegrowing, then loop over the String characters and define the character in switchand replace it with an escaped character. Here you can find here and here . But StringEscapeUtilsit’s easier to use in the long run.

+8
source
public static String encodeHTML(String s)
{
StringBuffer out = new StringBuffer();
for(int i=0; i<s.length(); i++)
{
     char c = s.charAt(i);
            if( c=='<' )
            {
               out.append("&lt;"+(int)c+";");
            }
            else if(c=='>'){
                 out.append("&gt;"+(int)c+";");
            }
            else
            {
                out.append(c);
            }
}
return out.toString();

}

+1
source

, :

:

  • char is > output &gt;
  • char < &lt;
  • char &amp;
  • char unicode 32..126 output &#...; ... - char unicode.
  • else output char
0
source

Source: https://habr.com/ru/post/1757464/


All Articles