Think about what your code does. Actually, don't think about it, look at it. Open the source code of your page when it's displayed in the browser. Assuming the session attribute contains the value hello
, then your code will generate
<script type="text/javascript">
var test = hello;
document.write (test);
</script>
So the value will be interpreted as a JavaScript variable. And since you most likely don't have defined a variable called hello
, this results in undefined
.
However if you now only add quotes:
var test = "<%= session.getAttribute( "mySessionVar" ) %>";
then you'll still not be safe, because since the value comes from your user, as you say, then it can contain not only quotes itself but also more JavaScript code or even HTML code.
Imagine your user enters "; while(1) {alert('This site is crap!')};</script><h1>This site is crap!</h1>
(notice the quote character at the start!)
Leading to your source code containing:
<script type="text/javascript">
var test = ""; while(1) {alert('This site is crap!')};</script><h1>This site is crap!</h1>
And now your site will not only display "This site is crap!" in large letters, but will lock the user in an endless loop of alert boxes. (That is called Cross-Site Scripting)
Number one rule in web development, NEVER EVER output anything (especially not user input) that hasn't been escaped properly. Use StringEscapeUtils.escapeJavaScript for JavaScript and c:out
for HTML.
See also for example:
PS: I hope, if you are using a database, you are escaping your SQL statements correctly, otherwise people can very simply get access to your database and server (called SQL injection)