Main Tutorials

How to escape special characters in java?

In Java, we can use Apache commons-text to escape the special characters in HTML entities.

Special characters as follow:

  1. <
  2. >
  3. &
pom.xml

  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>1.8</version>
  </dependency>
EscapeSpecialChar.java

package com.mkyong.html;

import org.apache.commons.text.StringEscapeUtils;

// @deprecated as of 3.6, use commons-text StringEscapeUtils instead
//import org.apache.commons.lang3.StringEscapeUtils;

public class EscapeSpecialChar {

    public static void main(String[] args) {

        String testStr = "< > \" &";

        System.out.println("Original : " + testStr);

        System.out.println("Escaped : " + StringEscapeUtils.escapeHtml4(testStr));

    }
}

Output


Original : < > " &
Escaped : &lt; &gt; &quot; &amp;

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Badal
8 years ago

Actually the output is not right. Escaped should be < > " &.

Abhishek
4 years ago

Facing problems with special characters. Have two application one connected to other through rest.
SpringRestController.java snippet below
Gson gson1 = new GsonBuilder().setDateFormat(“dd/MM/yyyy HH:mm:ss”).setPrettyPrinting().disableHtmlEscaping().create();

return gson1.toJson(lstCertNotification);

so inside lstCertNotification we have another property strCertId for which the Value is N°123 …this degree symbol is creating problem

Client code snippet below
ClientResponse response = EECPCommonHelper.clientGetResponse(“searchCertificates”).put(ClientResponse.class,jsonString);;
if (response.getStatus() != 200) {
if(response.getStatus()==401){
try {
FacesContext.getCurrentInstance().getExternalContext().redirect(“Error401.html”);
} catch (IOException e) {
e.printStackTrace();
}
}else
throw new RuntimeException(“Failed service call: HTTP error code : “+ response.getStatus());
}else{
response.bufferEntity();

Object strLstVendorServices = response.getEntity(Object.class);

//response.getEntity(response.getEntityInputStream(), List.class);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String entity = mapper.writeValueAsString(strLstVendorServices);
TypeToken<List> token = new TypeToken<List>() {};
lstCertNotification = gson.fromJson(entity, token.getType());

in the client i am getting it as a N?123
the application which has the springrest controller it is printing perfectly with degree symbol but in client portal while rest response it is the problem

Kiril ISAKOV
6 years ago

Reference is a dead link.
I found the working link: http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html
Please edit.
All best.

priya
9 years ago

I want to know about this library commons-lang.jar . I am working on jboss-eap-5.1 on server. Can I download this version jar file?

michael
10 years ago

how to escape special characters from xml file?

jesus israel perales martinez
8 years ago
Reply to  michael

StringEscapeUtils.escapeXml(string);

Swati Rohilla
12 years ago

This is the BEST example. It helped me alot. Thanks alot. Big thanks to you.

bluelurker
7 years ago

How to escape special characters only from the value. ?
hello$ed
should be helloed