...">

Declaring a global variable in java scriptlets

I have html file:

<html>
<body>
<% int i=1; %>
<span name="page2"></span>
</body>
</html>

      

and in the span2 page of that file, I inserted a new page like this:

<html>
<body>
<% if(i=1) { %>
<p>1</p>
<% }
else { %>
<p>2</p>
<% } %>
</body>
</html>

      

I am working in Websphere factory portlet to insert second page into first page.

The problem is that the variable "i" in the second file cannot be resolved.

+3


source to share


2 answers


Each jsp file is separately compiled to server

. when the second file is compiled it doesn't know the declaration int i

.

By default, it is stored in the field page

,

The scope of the page means the JSP object can only be accessed from within on the same page where it was created



You can install it,

application.setAttribute( "globalVar", i);

      

in the app area to access it through the app

+1


source


Anything you write inside scriplet will become the content of the Servlet service method.

So,

<% int i=1; %>

      

will be

public void service(request,response){
   int i=0

}

      

You can use JSTL tags because it is better to avoid using scripts



<c:set var="i" value="1" scope="request/session/application"/>

      

Your whole example without using a script would look like this

<!--You have to import JSTL libraries-->
html>
<body>
<c:set var="i" value="1" scope="application"/>
<span name="page2"></span>
</body>
</html>

      

Accessing it in another JSP.

<html>
<body>
<!-- Expression language-->
<p> ${applicationScope.i eq 1?1:2} </p>
</body>
</html>

      

+2


source







All Articles