Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 859
Rey Rajesh Avatar asked Feb 20 '26 18:02

Rey Rajesh


2 Answers

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

So

<% int i=1; %>

will be

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

}

You can use JSTL tags because it is best practice to avoid usage of scriplets

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

Your whole example without using script becomes 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 into another JSP.

<html>
<body>
<!-- Expression language-->
<p> ${applicationScope.i eq 1?1:2} </p>
</body>
</html>
like image 119
Shoaib Chikate Avatar answered Feb 23 '26 07:02

Shoaib Chikate


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

like image 25
Santhosh Avatar answered Feb 23 '26 07:02

Santhosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!