File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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 %>
<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?

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: 642
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
[ 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

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.
I agree. Here's the link:
subject: Can I declare a variable in an included page?
It's not a secret anymore!