Search code examples
javahtmlscriptlet

Declaring a global variable in java scriptlets


I have a html file like this:

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

and in the span page2 of the above 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 portlet factory to insert the second page into first page.

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


Solution

  • Each jsp file is individually compiled in the server . when the second file is compiled it doesnt know the declaration of int i.

    By default it is stored to the page scope ,

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

    You can rather set it ,

    application.setAttribute( "globalVar", i);
    

    in the application scope to access it through out the application