Sunday, 5 January 2020

How to escape html in java?


Using Apache commons-text
String escapedText = StringEscapeUtils.escapeHtml4(str);

App.java
package com.sample.app;

import org.apache.commons.text.StringEscapeUtils;

public class App {

 public static void main(String args[]) {
  String str = "<html> : This is the starting tag.  <body>All the body goes here </body>";

  String escapedText = StringEscapeUtils.escapeHtml4(str);
  
  System.out.println(escapedText);
 }

}

Output
&lt;html&gt; : This is the starting tag.  &lt;body&gt;All the body goes here &lt;/body&gt;

Using HtmlUtils.htmlEscape of spring web utils
String escapedText = HtmlUtils.htmlEscape(str);

App.java
package com.sample.app;

import org.springframework.web.util.HtmlUtils;

public class App {

 public static void main(String args[]) {
  String str = "<html> : This is the starting tag.  <body>All the body goes here </body>";

  String escapedText = HtmlUtils.htmlEscape(str);
  
  System.out.println(escapedText);
 }

}

Output
&lt;html&gt; : This is the starting tag.  &lt;body&gt;All the body goes here &lt;/body&gt;



You may like

No comments:

Post a Comment