Tutorial :why is '<' showing as <


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'


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



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


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


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.


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.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »