September 29, 2014

Lifecycle of a JSP- part I



JSPs are basically dynamic HTML pages, the dynamic content being provided by specific libraries(JSTL or Java Standard Tag Libraries ) expressions and directives ( page,import,include ). The specifics of these elements I will discuss in future posts.

This post will deal with the life-cycle of a JSP  in Apache Tomcat. The questions that will be answered will be
  • Does a JSP get converted in .java file. If so,when ? during server start-up or every time a JSP page is requested by the browser.
  • Which component of Tomcat does the conversion? Where does this so call JSP engine reside in Tomcat?
  • What happens after the conversion ? Where do the converted files reside ? 
  • When does a JSP page finally get destroyed ?
  • Dynamic and Static inclusion


So let's begin with answering the first question:

Yes. A JSP page gets  translated into a Servlet java file and corresponding class file.This is known as the translation & compilation phase. 

e.g. login.jsp --> login_jsp.java --> login_jsp.class

The java and class files are stored in 'work' directory in Tomcat

Now, these 2 phases can happen when the application is deployed. The container translates & compiles all jsp into class files. This is called pre-compilation and provides better performance since time is not spent during page request.

But these 2 phases can also happen when a request for jsp is made. The container checks if the jsp file is newer than the class file. if it is, then it translates & compiles again before serving the request.

Sometimes, a jsp file needs to be included into another jsp file. This can be done by

<%@include directive or <jsp:include action

The difference b/w the two is that using the former, the jsp gets included into its parent jsp during application deployment & hence is  best suited for including static content. That's why only relative path w.r.t the parent jsp is enough for inclusion e.g

<%@include file="./footer.jsp" %>   if parent jsp and footer.jsp are in same directory.

Using the latter,the jsp gets included during request time i.e. when the client requests the parent jsp file. This is called dynamic inclusion and is suited for jsp with lot of dynamic content. This include action also can cause performance overhead since inclusion happens at run time. So use it wisely i.e.for including jsp with a lot of dynamic content.

Also, since inclusion happens at run time, the context relative path is used.

<jsp:include page=/XXX/footer.jsp />  if footer.jsp is present in dir 'XXX' of the web-application

No comments:

Post a Comment