3

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

Rey Rajesh
  • 502
  • 1
  • 6
  • 25

2 Answers2

3

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>
Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
  • 1
    To access you just need you use scope which you are using. For e.g ${requestScope.i} or ${sessionScope.i} And you should avoid using scriptlets. Never write any Java code in JSP. – Shoaib Chikate Nov 04 '14 at 06:34
2

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

Santhosh
  • 8,181
  • 4
  • 29
  • 56