Thats because there is a slight difference between how the two includes work.
The include directive, ie. <%@ include file="..." %> is used at translation time. [When the translator generates servlet code from your jsp file]
At translation time, above directive is replaced by the contents of the file that you specify in the file attribute.
So, in your included file, if you are referring to a variable declared in the including file, it works because while compiling, the including and included file are part of the same servlet.
The inlude action, i.e. <jsp:include page="..." /> comes into action at request time.
So when you are using include action, the above line isnt replaced with the contents of the included page as in case1. Instead, it is replaced by requestDispatcher.include() call.
Two servlets are formed. One for the including page and the other for the included page.
At run time, when a request comes to first page which contains the <jsp:include.../>, internally, the container sends a request to the second page. the output of this second page replaces the <jsp:include...> tag that you write.
In this case if you notice, since there are two different servlets, variables declared in one will not be available in the second.
Hence the error that you are getting.
In a nutshell...
Include directive is
Includion of the page contents.Happens at translation time.
Include action is
Inclusion of the output of the page.Happens at request time.
Repercurssions:
If you use directive:
Code in page 2 can use all the varilables and methods from page 1 because eventually both the pages are compiled into single servlet.Slightly improved performance compared to action since there is no request time calling of requestdispatcher.include()If your page 2 is going to change frequently, you yourself will have to take care of translate & compile page 1. Unless you do that, the changes in page2 wont be reflected in page1 If you use include action:
You are loosely coupling the two pages which arent dependent on each others variables.Useful when you know your page 2 is going to change frequently.You dont have to worry about explicitly compiling page 1. It is not required.You may face standard "Buffering issues".