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

8 comments on “How to escape special characters in java?

  1. 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

Leave a Comment

Your email address will not be published. Required fields are marked *