I'm a php guy, but I have to do some small project in JSP. I'm wondering if there's an equivalent to htmlentities function (of php) in JSP.
Asked
Active
Viewed 7,505 times
4
-
See http://stackoverflow.com/questions/3636956 – Tim Sylvester Mar 25 '11 at 16:51
3 Answers
8
public static String stringToHTMLString(String string) {...
The same thing does utility from commons-lang library:
org.apache.commons.lang.StringEscapeUtils.escapeHtml
Just export it in custom tld - and you will get a handy method for jsp.

Aleksei Egorov
- 801
- 9
- 16
3
public static String stringToHTMLString(String string) {
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++)
{
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with , if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
sb.append(" ");
}
else {
lastWasBlankChar = true;
sb.append(' ');
}
}
else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append(""");
else if (c == '&')
sb.append("&");
else if (c == '<')
sb.append("<");
else if (c == '>')
sb.append(">");
else if (c == '\n')
// Handle Newline
sb.append("<br/>");
else {
int ci = 0xffff & c;
if (ci < 160 )
// nothing special only 7 Bit
sb.append(c);
else {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(new Integer(ci).toString());
sb.append(';');
}
}
}
}
return sb.toString();
}

Florin
- 1,379
- 3
- 16
- 21
-
-
I agree with what Florin has done. I have not seen a buit-in function in Java with JSP or JSTL that does what you're asking. – codefin Nov 30 '08 at 14:11
2
I suggest using escapeXml set to true attribute of JSTL's directly in JSP
<c:out value="${string}" escapeXml="true" />

Miron Balcerzak
- 886
- 10
- 21