Reputation: 101
I have this JavaScript code:
<script>
function greetings() {
var hash = window.location.hash.substring(1);
if (hash != "") {
var name = "<%= Encode.forJavaScriptBlock(hash) %>";
document.write("<h1> Hello " + name + "!</h1>");
}
else {
document.write("<h1>Welcome Back!</h1>");
}
}
greetings();
</script>
When I run this I receive the following error related to the declaration line of the name variable:
hash cannot be resolved to a variable
I don't understand why as the hash variable seems in scope to me.
Upvotes: 0
Views: 885
Reputation: 64949
It seems you have some misunderstanding of when your Java and JavaScript code executes.
The code within your JSP gets compiled into Java code that will look something like the following:
out.println("<script>");
out.println(" function greetings() {");
out.println(" var hash = window.location.hash.substring(1);");
out.println(" if (hash != \"\") {");
out.print(" var name = \"");
out.print(Encode.forJavaScriptBlock(hash));
out.println("\";");
out.println(" document.write(\"<h1> Hello \" + name + \"!</h1>\");");
out.println(" }");
out.println(" else {");
out.println(" document.write(\"<h1>Welcome Back!</h1>\");");
out.println(" }");
out.println(" }");
out.println(" greetings();");
out.println("</script>");
The server doesn't process the JavaScript code within the <script>
element. To the server, that's just a load of text it sends straight to the browser without any further processing. However, within your JSP you have a scriptlet <%= Encode.forJavaScriptBlock(hash) %>
, and the contents of this does gets written into the compiled Java code. This line attempts to refer to a Java variable named hash
, but there is no such thing: whilst your JavaScript code does contain a variable named hash
, that (a) will never exist on the server, where your JSP runs, and (b) won't exist in the user's browser until the page has been sent to the browser, and that will be after the JSP has finished running.
This is why you are getting the error you are.
Ultimately, it seems you are trying to prevent malicious data being inserted into your web page, but without quite understanding how to do this. It seems you would be better off following Rule #6 from the cheat sheet you link to, by having an <h1>
element somewhere in your page, with an ID, and modifying your JavaScript function to change the text content of this instead, i.e.
<h1 id="greeting-message">
<script>
function greetings() {
var hash = window.location.hash.substring(1);
var greetingElement = document.getElementById("greeting-message");
if (hash != "") {
greetingElement.textContent = "Hello " + hash + "!";
}
else {
greetingElement.textContent = "Welcome Back!";
}
}
greetings();
</script>
Upvotes: 1