Method for escaping HTML in Java

0 votes

Is there a recommended way to escape <, >, " and & characters when outputting HTML in plain Java code? (Other than manually doing the following, that is).

String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = source.replace("<", "&lt;").replace("&", "&amp;"); // ...
Jan 9, 2019 in Java by Sushmita
• 6,890 points
1,435 views

1 answer to this question.

0 votes

242

StringEscapeUtils from Apache Commons Lang:

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);

For version 3:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
// ...
String escaped = escapeHtml4(source);
answered Jan 9, 2019 by developer_1
• 3,300 points

Related Questions In Java

0 votes
1 answer

Overloaded method for null in Java

The method invoked here will be the ...READ MORE

answered May 23, 2018 in Java by code.reaper12
• 3,470 points
148 views
0 votes
1 answer

I am learning looping statements. Can you tell me how 'for-each' works in Java?

While programming we often write code that ...READ MORE

answered Apr 17, 2018 in Java by Rishabh
• 3,580 points
135 views
0 votes
2 answers

What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

answered Aug 23, 2018 in Java by Daisy
• 8,090 points
1,418 views
0 votes
1 answer

concat() vs “+” operator : In Java for String concatenation

Basically, there are two important differences between ...READ MORE

answered Apr 27, 2018 in Java by Rishabh
• 3,580 points
2,108 views
0 votes
1 answer

What is $route service in AngularJs?

$route is used for deep-linking URLs to controllers ...READ MORE

answered Feb 10 in Angular by Niroj
• 45,880 points
80 views
0 votes
1 answer

Error:Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

Hii @kartik, I was also facing the same ...READ MORE

answered May 13 in Database by Niroj
• 45,880 points
219 views
0 votes
1 answer

How to detect a SQL table's existence in Java?

Hello, Depending on the DB, you can do ...READ MORE

answered May 13 in Database by Niroj
• 45,880 points
83 views
0 votes
1 answer

Error:npm install won't install devDependencies

Hello @kartik, Try: npm install --only=dev If you are worried ...READ MORE

answered Jul 15 in Node-js by Niroj
• 45,880 points
91 views
0 votes
1 answer

Xpath in Java for accessing OWL Document

Don't query RDF (or OWL) with XPath In ...READ MORE

answered Feb 27, 2019 in Java by developer_1
• 3,300 points
147 views
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,090 points
1,756 views