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:
- <
- >
- ”
- &
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 : < > " &
Actually the output is not right. Escaped should be < > " &.
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
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.
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?
how to escape special characters from xml file?
StringEscapeUtils.escapeXml(string);
This is the BEST example. It helped me alot. Thanks alot. Big thanks to you.
How to escape special characters only from the value. ?
hello$ed
should be helloed