5

I have a scenario where i need to compare javascript varibable with java object inside scriptlet of jsp page. How can i get javascript variable in the jsp scriptlet or the other way will also work for me(getting arraylist object value in javascript).

participantjava
  • 195
  • 1
  • 2
  • 16

4 Answers4

6

It is possible, two ways to assign javascript variable value to jsp scriptlet.

First Way Demo1.jsp

<script>
    var name = "Gautam";
</script>
<%
    String str = "<script>document.writeln(name)</script>";
    out.println("value: " + str);
%>

Second Way Demo2.jsp

<html>
<script>
    function call() 
    {
        var name = "Gautam";
        window.location.replace("Demo2.jsp?name=" + name);
    }
</script>
<input type="button" value="Get" onclick='call()'>
<%
    String name = request.getParameter("name");
    if (name != null) 
    {
        out.println(name);
    }
%>
</html>
Gautam Viradiya
  • 517
  • 7
  • 11
-1

If you need a variable from server in JavaScript, use Expression Language (assuming this variable is stored as request, session, application or page attribute):

<%@taglib uri="http://example.com/functions" prefix="f" %>

<!-- ... -->

function showValues(str) {
    var empListLength = ${empty empList ? 0 : fn:length(empList)};
}

If you need a variable from JavaScript in your scriptlet, you're out of luck, this is impossible. The only way to get a variable from an external resource is as a request parameter.


I omit the answer using scriptlets directly because its usage is highly discouraged.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • @participantjava no, you can't. You must understand that Java runs on server side while JavaScript runs on client side. It would be better if you explain what you're trying to achieve. – Luiggi Mendoza Apr 08 '14 at 03:05
-1

If you need a variable from server in JavaScript, use Expression Language (assuming this variable is stored as request, session, application or page attribute):

If you need a variable from JavaScript in your scriptlet, it is impossible. The only way to get a variable from an external resource is as a request parameter

Stacked
  • 6,892
  • 7
  • 57
  • 73
-2

Javascript is run in the browser and JSP's are run on the server. Declare the java script variable using scriptlets and then compare on the browser:

var x = <%= str%>

Then you can compare in the browser during execution of the javascript. Other than that scriptlets are unaware of anything in JavaScript because it has to be run in the broswer and by that time the scriptlets have already been executed and converted to html, javascript, or css.