Question

I am new to jsp. I am writing one "declaration" and one "scriptlet" in a jsp page.

But the variables i created in declaration and in "scriptlet" does not store in any one of the

scope. ie page scope,request scope,application scope.why.

Here is my following jsp file named as "success.jsp",

     <%! int x=20; %>//x is not created in any scope.
    <% int y=30; %>// y is not created in any scope.

   <script>

  var p="${x}";//here,variable p does not get any value.
  var q="${y}";//here,variable does not get any value.

  </script>

why the variables "x" and "y" does not created in any one of the scope.And how to get the values stored in "x" and "y" variables.

No correct solution

OTHER TIPS

I think the best way to start understanding jsps is that they are secretly being interpreted into java classes. But more specifically: They are being put into a function that is writing out the html line by line, after evaluating each line. Hence why you can have the <% %> tags. Now, because of that, the <% %> tags are actually lines that are evaluated but not written to the html. The evaluations are stored in the scope of the resulting java method. So what ends up happening looks something like:

public void SendHtmlPage() {
  int x=20; 
  int y=30; 

  Print("<script>");

  Print("var p=\"${x}\"\;"); //This gets evaluated to getSession.getAttribute("x")
                             //Since there is no x in the session, it returns null
  Print("var q=\"${y}\"\;"); //Same here

  Print("</script>);
}

So. That is why x and y aren't known inside your scriptlet. However, there are ways to save the method scoped variables to session scope. Check this out: I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Good luck and happy coding. :)

change your code like this

var p = <%=x%>;
var q = <%=y%>;

As you noted, the variables created by the jsp-scriplet code <%! int x=20; %> are not available in any scope, as they are directly declared inside the compiled jps page (any jsp page internally compiled to a servlet class).
For using the variable x in the rest of the jsp page you have two different options:

  1. Use jsp-scriplet expressions <%= x %> and in this case the code inside your javascipt fragment would be:

    var p = "<%= x%>";
    var q = "<%= y%>";

  2. Manually save the variables x, y inside the pageContext scope, in this way they become available from the EL:

    <%
    int x=20;
    int y=30;
    pageContext.setAttribute("x", x);
    pageContext.setAttribute("y", y);
    %>

As a note, be aware that <%! int x = 20; %> is different from <% int x=20; %>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top