1

I am attempting to call a java class function inside javascript that is inside a jsp page. I've imported it...

<%@ page language="java" import="myPackage.*"%>

I've constructed the class

<% 
    myClass myJavaInstance =new myClass(); 
    System.out.println("this worked!"); 
%> 

I have a bit of javaScript with an alert message in it

<script>
    alert("hello ");
</script>

But when I add this line...

var thisHere = <%= myJavaInstance.getName() %>

before the alert it doesn't show up

<script>
    var thisHere = <%= myJavaInstance.getName() %>
    alert("hello ");
</script>

If I put it after the alert it shows up

<script>
    alert("hello ");
    var thisHere = <%= myJavaInstance.getName() %>
</script>

I know the method gets called because I put a println in it. What am I missing here? It should work right?

wjhplano
  • 611
  • 2
  • 13
  • 31
  • 1
    possible duplicate of [inline java makes causing javascript to not execute](http://stackoverflow.com/questions/21022459/inline-java-makes-causing-javascript-to-not-execute) – Vinoth Krishnan Jan 09 '14 at 17:01
  • 2
    It seems the jsp doesn't render `var thisHere = <%= myJavaInstance.getName() %>` into proper javascript and therefore the browser can't execute it. What is the return value of `myJavaInstance.getName()`? – Sotirios Delimanolis Jan 09 '14 at 17:02

2 Answers2

3

The result of myJavaInstance.getName() is probably a string like "Nikos". The rendered output in JS will be:

var thisHere = Nikos

Which is not valid JS (Nikos is undefined). So surround it with quotes:

var thisHere = "<%= myJavaInstance.getName() %>";

Additionally you should escape the string for any quotes found inside it.

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
1

Use the console. Looks like you have a syntax error, you need to put quotes around strings in javascript. When the script errors out it stops executing the rest of the script. That's why when you put it before the alert and it errors out it wont execute the alert, but if you put it after it does the alert and then errors out.

<script>
    var thisHere = "<%= myJavaInstance.getName() %>"
    alert("hello " + thisHere);  
</script>