tags:

views:

369

answers:

6

I am outputting a string form my java class like this

String numQsAdded = "<div id='message1'>"+getQuestion()+"</div>";

This string is being sent back to the client side as a XMLHttpRequest. So, in my jsp page I have a javascript alert method that prints out the string returned from the server. it translates '<' to &lt; and '>' to &gt;

how can i avoid this?

I have tried changing my string to:

String numQsAdded = "&lt;div id='message1'&gt;"+getQuestion()+"&gt;/div&lt;";

but this has even worse effects. then '&' is translated as 'amp'

+3  A: 

&lt; is the way to show "<" in html, which is produced from XMLHttpRequest. try using XMLRequest

KM
More specifically, < and > are XML entities and not HTML entities.
DrJokepu
@DrJokepu: They are HTML entities, not XML entity. XML use x;. To use < in XML, you need a DTD.
J-16 SDiZ
@J-16 SDiZ you're wrong. Read the XML spec. http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent
ykaganovich
+5  A: 

XMLHttpRequest encodes the string before sending it. You will have to unescape the string. on the client side javascript, try using:

alert(unescape(returned_string))
Ryan Oberoi
I don't think this will work for XML entities as (un)escape functions work on url encoding - e.g. replacing space with %20. Just try running alert(unescape("<")); (but not in onclick="" tag, in plain script definition.
Rashack
A: 

I don't think you can avoid that. It's how "<" is represented in HTML, and the result would be OK on your HTML page.

paradisonoir
+2  A: 

It is the entity reference for "<" while &gt ; is the entity reference for ">" you will need to unescape the string using the unescape() method

Matthew Vines
A: 

It might be better to send back a raw string with your message, and leave the client Javascript to create a div with class message1 to put it in. This will also help if you ever decide to change the layout or the style of your notices.

Paul Fisher
+2  A: 

Paul Fisher's answer is the right one. I'll take a moment to explain why. HTML-Encoding of content from the server is a security measure to protect your users from script injection attacks. If you simply unescape() what comes from the server you could be putting your users at risk, as well as your site's reputation.

Try doing what Paul said. It's not difficult and it's much more secure. Just to make it easier, here's a sample:

var divStuff = document.createElement('div');
divStuff.appendChild(containerElement);
divStuff.id = 'message1';
divStuff.innerHTML = getQuestion();

This is much more secure and draws a better separation for you presentation layer in your application.

Joe Davis
In more complex Ajax cases, this is simply not possible. Rich UI elements are sent downstream. Security is mitigated as long as the content is generated on the server and stripped of tags/javascripts supplied from the external inputs.
Ryan Oberoi