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?

2
  • 1
    possible duplicate of inline java makes causing javascript to not execute Commented Jan 9, 2014 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()? Commented Jan 9, 2014 at 17:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.