June 27, 2014

Difference between static and dynamic inclusion in JSP

Why we need inclusion in JSP pages?
Main purpose of using inclusion in JSP pages is to reduce code redunancy and to promote reusability.

e.g
In many web applications, there are some common elements you need to display in many pages. For example, company logo, copy right information, and so on. Instead of reproducing those common pieces in each of JSP pages, you can factor those common code into other files and include them into JSP pages using inclusion mechanism provided by JSP engine. The application's maintainability (you just need to make changes in only one palce) and reusability gets improved. e.g header and footer's

Types of Inclusion:
JSP engine supports two include mechanisms: include directive and include action (or jsp:include).

Difference between static and dynamic inclusion in jsp..
1. Static inclusion is Include Directive and dynamic inclusion is Include Action.
2. The syntax for static include is

< %@ include file=”filename.jsp” % > .

Where as the syntax for dynamic include is

< jsp:include page=”filename.jsp” / >

3.The include directive allows a static resource to be included in the page at translation time (JSP compile time), and it is then parsed/translated along with the rest of the JSP. The resulting page as one page therefore creating one corresponding servlet. It’s something like a copy and pasting the text from your include page right into your JSP.

The include action on the other hand is a request time include, the included file is treated a separate servlet which is executed at request time and its output "chained" to the including servlet. The output produced by that (second) JSP is included without being parsed or translated by the first JSP.

4. Static include cannot have a dynamic filename. This is because the servlet container needs the files for inclusion, at translation phase itself. But dynamic include can have a dynamic filename. Here the file is getting included at runtime.
5. Static include cannot accept a parameter. But dynamic include can accept a parameter..

e.g
< jsp:include page="file.jsp" >
< jsp:param name="firstname" value="Chaitanya" / >
< jsp:param name="middlename" value="Pratap" / >
< jsp:param name="lastname" value="Singh" / >
< /jsp:include >

6. Static includes are faster than dynamic includes.

No comments:

Post a Comment