Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to HTML-encode in the JSP expression language?

Consider the following piece of JSP:

<param name="FlashVars" value="${flashVars}" />

The value of ${flashVars} contains ampersands and needs to be encoded before it is output. Instead, JSP expects the value of ${flashVars} to be a piece of HTML and outputs the ampersands verbatim, resulting in bad HTML.

I found out that I can get the value to be encoded if I write it like this:

<param name="FlashVars" value="<c:out value="${flashVars}"/>" />

But this looks really ugly and confuses my IDE to boot. Is there a better way to get the same result?

like image 708
Martijn Avatar asked Dec 24 '10 13:12

Martijn


People also ask

How do you escape HTML special characters in JSP and Java?

The fn:escapeXml() function escapes characters that can be interpreted as XML markup.

What is ${} in JSP?

Simple Syntax and []. These two operators allow you to access various attributes of Java Beans and built-in JSP objects. When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson.

What is HTML encoding and decoding?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.


1 Answers

Use fn:escapeXml().

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<param name="FlashVars" value="${fn:escapeXml(flashVars)}" />
like image 151
BalusC Avatar answered Oct 09 '22 03:10

BalusC