Blog

JSP Pages, Do not get too used to c:out!

by | Jun 10, 2011 | Webapps | 0 comments

I was always one to go ahead and use <c:out> to display model data in my JSP pages.  Never had a reason not to!  Well, I recently had a reason…

 

As I mentioned in my last post, I am working on a web application that uses several jQuery libraries – another one is AutoSuggest, a handy-dandy plugin for auto-completion.  The AutoSuggest library can have pre-populated data, but it expects a JSONArray type. Normally XMLHttpRequest form submits work great, and data is returned to my JSP page with no page refresh, but sometimes I need to use normal HTML form submits (i.e. for file uploads), where my data is returned as ModelandView to a JSP page (refresh needed).

I had trouble with the latter – displaying JSONArray data in my JSP page because I was always setting the value to a javascript variable using <c:out>.  You can see below where I had some trouble.

OLD:

[cc lang=”javascript” escaped=”true” nowrap=”false”]

Option 1:

var existing_docApprovers = ‘<c:out value=”${existing_docApprovers}” escapeXml=”false” />’;

Option 2:

var existing_docCases = “<c:out value=’${existing_docCases}’ escapeXml=’false’ />”;

[/cc]

Problems –

  1. If I have single quotes around the <c:out> as in Option 1, this preserves the JSON with proper syntax around all properties/values.  Great – but not if there’s a in the JSON itself anywhere.  This results in a javascript parsing error.
  2. If I change it to double quotes around the <c:out> as in Option 2, same problem (“’s in the JSON itself).  This results in a javascript parsing error.
  3. If I change to escapeXml=”true” in either Option 1 or 2, the special HTML formatting is preserved, but then it’s not valid JSON.

What I needed to do was use the bare EL statement to leave the contents exactly as is -> a JSONArray!

NEW:

[cc lang=”javascript” escaped=”true” nowrap=”false”]

// default JSON Array as empty
var existing_docApprovers = [];
<c:if test=”${ (not empty existing_docApprovers) }”>existing_docApprovers = ${existing_docApprovers};</c:if>

[/cc]

 

Of course, I also needed to set existing_docApprovers to an empty array, just in case ${existing_docApprovers} was null or undefined or just did not exist, or I would get an javascript error setting a variable to nothing.

This Oreilly article explains the problem I had very well – I’ll paraphrase here to emphasize:
“I’ve recently seen it suggested that JSP pages should replace all <c:out/> with ${…}. This could have serious side-effects if the content of the variables presented is not considered carefully with respect to escaping.”

 

 

Categories

0 Comments

Submit a Comment

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