Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a JSP variable from JavaScript

How can I read/access a JSP variable from JavaScript?

like image 952
Siddiqui Avatar asked Jan 26 '11 11:01

Siddiqui


People also ask

Can we use JSP variable in JavaScript?

You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document. You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS.

Can we access JavaScript variable in JSP and vice versa?

JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP.

How does JSP work with JavaScript?

JSP is technology based on servlet container and Java EE specification by Oracle (then Sun Microsystems). JavaScript is a scripting language. It also adds dynamic web content to the web pages but has limited features. Adds dynamic functional aspect to the static web pages with a rich user experience.


1 Answers

alert("${variable}"); 

or

alert("<%=var%>"); 

or full example

<html>  <head> <script language="javascript">   function access(){    <% String str="Hello World"; %>    var s="<%=str%>";     alert(s);  }   </script>  </head>   <body onload="access()">  </body>   </html> 

Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities

like image 52
jmj Avatar answered Sep 19 '22 07:09

jmj