How can I dynamically, include a file in JSP?
If I use <jsp:include > syntax, then I have to redefine all the variables in the include page. And also it gives error as Attribute not found.
Prateek, using <jsp:include ../> includes the content generated by the referenced servlet/jsp, not the file itself. It's rather like make a call to a method that returns a value. You shouldn't have to rename variables. As for the 'Attribute not found', check the syntax for you <jsp:include .../> tag.
The include "directive": <%@ include file=”_filename.jsp” %> includes the content of the specified file at the time the page is converted to a servlet (this is usually done when the page is accessed for the first time ever on a web site). The included content is “pasted” into the main page, and then the combined single file is compiled by the web server, into a single servlet.
Any scripting variables defined in one file, or any beans declared, are available to the entire set of files (main page and all included files), so all names have to be unique.
Also, the name of the included file must be known to the web container before running any Java within the main page, as the inclusion is done before the page is compiled.
Some web containers detect the changes in the included files, so if you change the content of an include file, when the main page is accessed again, the main page and includes are combined and compiled into an updated servlet. Now this isn’t part of the J2EE specification, so this is not always the case. You may have to wait a while for the changes to be made, or you may have to update the main page, or remove the class files generated for the main page in order to see the change.
The include "action": <jsp:include page=”_filename.jsp” flush=”true”%> includes the response generated by executing the specified page (a JSP page or servlet) when requested by the user.
This means that scripting variables, and any beans declared need not have unique names. The variable and bean names used in one page cannot be seen by any other page in the main or included files (other than placing the variable or bean with request, session or application scope).
Also the page name to be included can be as a request time attribute, for example, the Java code in the main page could specify two different include files based on conditional logic, and depending on the outcome of the logic, either of the files could be loaded. This cannot be done with the include directive.
Use the include directive if the file doesn’t change much. It is the quickest at runtime. If your web container doesn’t notice changes in the included files, delete the main page class file.
Use the include action for content that changes often, or when the page to be included can only be evaluated at runtime.