Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing java variable from javascript on same jsp

Tags:

java

jsp

Is it possible to access a String type variable defined in jsp from a javascript on the same page?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">  
foo();
function foo()  
{  
var value = "<%=myVar%>";  
alert(value);   
}  
</script>  
</head>
<body>

<%

String myVar="blabla";
%>

</body>

</html>

In eclipse I am getting an error

myVar cannot be resolved to a variable
like image 807
Vge Shi Avatar asked Sep 24 '13 19:09

Vge Shi


People also ask

How can I access JavaScript variables in JSP?

JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP. But you can store needed data in hidden fields, set its value in client and get it on server over GET or POST.

Can we use JavaScript on JSP page?

Yes, We can use javaScript with JSP page. As we know that javaScript is a Client-side script and JSP is a Server-side so we can attach a form validation to a JSP page to redirect HTML page and javaScript content. -Before submitting page to web server, it should be validate HTML field data.

Can we use JavaScript variable in Java?

Using DWR framework, you can send javascript variables to java.

How does JSP work with JavaScript?

The easiest way to see the difference is one simple sentence: JSP is the server-side scripting language i.e. it runs on the server while JavaScript runs on the client. As a result, JSP is more used to change the content of a webpage, and JavaScript for the presentation. It is quite common to use both on the same page.


1 Answers

This won't work since you're trying to use an undefined variable. The code is generated like this:

... = myVar;
//...
String myVar = "blabla";

Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:

<c:set name="myVar" value="blabla" />
<script type="text/javascript">  
    foo();
    function foo() {
        var value = "${myVar}";
        alert(value);
    }
</script>

If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:

var value = "<c:out value='${myVar}' />";

More info:

  • How to avoid Java code in JSP files?
like image 146
Luiggi Mendoza Avatar answered Sep 24 '22 23:09

Luiggi Mendoza