GeeCON Prague 2014*
The moose likes JSP and the fly likes Can I declare a variable in an included page? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » JSP
Bookmark "Can I declare a variable in an included page? " Watch "Can I declare a variable in an included page? " New topic
Author

Can I declare a variable in an included page?

Sandesh Tathare
Ranch Hand

Joined: Jun 22, 2003
Posts: 82
Hi All,
--------------- welcome.jsp ---------------
<%! int counter = 5; %>
counter: <%= counter %>
</br>
<jsp:include page="index.jsp"/>
--------------- welcome.jsp ---------------
--------------- index.jsp ---------------
<%! int counter = 10; %>
Welcome to Index.jsp</br>
counter: <%= counter %>
--------------- index.jsp ---------------
When I request for welcome.jsp, following is output shown on browser:
counter: 5
Welcome to Index.jsp
counter: 10
I read that we can't declare a variable in an included page using include directive, if it is already declared in the including page since 2 page constitute a single translation unit.
So I was expecting an error instead of the above output.
Can any one throw some light on this?
Sandesh


Regards,<br />Sandesh<br />(SCJCP, SCWCD, SCBCD - 99%, OCP-1)<br /> <br />Either find a way or create one.
Praful Thakare
Ranch Hand

Joined: Feb 10, 2001
Posts: 637
Sandesh,
As you are using jsp:include which is runtime player,i.e it will copy output of included jsp in outputstream at runtime there is no error at compile time.
Instead if you use
<%@ include file="Index.jsp/" %> you will get the error you want
Cheers
Praful
[ November 17, 2003: Message edited by: Praful Thakare ]

All desirable things in life are either illegal, banned, expensive or married to someone else !!!
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Often called static and dynamic includes.
The static include (ie what you were trying to accomplish) is similar to the C programming language #include directive - all the code from the included source gets picked up and pasted into the original page. This single piece of code gets compiled and would cause the duplicate variable problem you wanted.
The dynamic include (ie what you actually had) generates two separate pieces of compiled code, they get run separately, and the output gets added together.
Dave
 
GeeCON Prague 2014
 
subject: Can I declare a variable in an included page?