File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JSP and the fly likes Assign Jsp variable to Javascript variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Assign Jsp variable to Javascript variable" Watch "Assign Jsp variable to Javascript variable" New topic
Author

Assign Jsp variable to Javascript variable

Muthiah Raja
Greenhorn

Joined: Feb 06, 2005
Posts: 9
I am trying to assign JSP String variable to Javascript variable.
For that i use the follwing code

<% String str="Raja"; %>
var s=<%=str%>;
alert(s);

But this code is not worked.

Kindly help me.
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
You did not declare the variable correctly. try this:

<%! String str="Raja"; %>


Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Vijesh Nair
Greenhorn

Joined: Nov 21, 2005
Posts: 1
Mr Bosun was asked to create a global variable in your jsp , but thats not a good practise.Why because while the jsp got converted to translated to servlet the global declarations will reside outside of service() method ,hence thats not thread safe.So for you the best practise is try to store the value of that variable in an hidden html element , then using the simple javascript norms you will be able to get the value of the variable.The JSP implicit objects can directly accessed in your javascript code.

Thanks Vichu.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Muthiah,
What you are doing is fine.
You just forgot to add the quotes to the Javascript literal.

var s = "<%=str%>";

Remember, you're not actually passing the value from the JSP realm to the Javascript realm. The output of your JSP's execution is Javascript code.
The best way to get your head around this is to view the HTML source from your browser often.

In the source you would have seen:
var s=Raja;

Instead of:
var s = "Raja";


And Vijesh is correct.
Declaring the string as an instance variable not only wouldn't have helped in this case, it most likely would have lead to threading problems in the application.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by Muthiah Raja:
I am trying to assign JSP String variable to Javascript variable.
For that i use the follwing code

<% String str="Raja"; %>
var s=<%=str%>;
alert(s);

But this code is not worked.

Instead of writting var s=<%=str%>;

I try var s='<%=str%>';
I try var s="<%=str%>";

this code also not worked.

Kindly help me.


It works for me:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assign Jsp variable to Javascript variable