Sunday 18 September 2011

JSP Life Cycle

Following diagram shows the different life cycle stages of jsp. Broadly, these stages can be classified into three.
  • Instantiation
  • Request Processing
  • Destruction






Instantiation:
When a web container receives a jsp request (may be first or subsequent), it checks for the jsp’s servlet instance. If no servlet instance is available or if it is older than the jsp, then, the web container creates the servlet instance using following stages.
  • Translation
  • Compilation
  • Loading
  • Instantiation
  • Initialization
Translation:
Web container translates (converts) the jsp code into a servlet code. This means that jsp is actually a servlet. After this stage, there is no jsp, everything is a servlet. This task will create a complete jsp page, by considering all included components. Here on, the static content and dynamic contents are treated differently. The resultant is a java class instead of an html page (which we wrote). This is how the structure of a jsp compiled into a java class will be.
package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class firstJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
  ............
  ............
  public Object getDependants() {
    return _jspx_dependants;
  }
  public void _jspInit() {
 ............
 ............
  }
  public void _jspDestroy() {
 ............
 ............
  }
  public void _jspService(HttpServletRequest request,
    HttpServletResponse response)
        throws java.io.IOException, ServletException {
 ............
 ............
  }
 ............
 ............
}
Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation is done using javac command. This will generate the byte code to be run on JVM.
Loading:
The compiled byte code is loaded by the class loader used by web container. This is a standard process of using any java class.
Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the initialization process. Initialization will make the ServletContext and ServletConfig objects available. One can access many attributes related to the web container and the servlet itself. After initialization the servlet is ready to process requests.
Request Processing:
Entire initialization process is done to make the servlet available in order to process the incoming request. jspService() is the method that actually processes the request. It prints the response in html (any other) format, using ‘out’ object.
Destroy:
Whenever the server is shutting down or when the server needs memory, the server removes the instance of the servlet. The destroy method jspDestroy() can be called by the server after initialization and before or after request processing. Once destroyed the jsp needs to be initialized again.
Just to summarize, web container handles incoming requests to a jsp by converting it into a servlet and then by using this servlet to generate the response. Also when the server shuts down, the container needs to clear the instances.
Controlling Life Cycle:
In above discussion, we understood that the jsp initialization phase happens when the first request hits the web container. This might take more time to present the response to the first user of jsp. It should be possible to keep initialized servlets ready to receive first request and immediately return response. This can be achieved by using the attributes provided by web and application server. The attribute can be “load-on-startup”, “pre compile” etc.

Elements of jsp are specified like an element in html or xml, i.e. with opening and closing tags. There are many types of elements in jsp. Here is the list of these elements.
  • Directives
  • Scriptlets
  • Actions
  • Expressions
  • Comments
  • Declarations
  • Template Text
These elements change the servlet generated by the container. Definitely these are used to change the behavior of dynamic contents of a jsp. Let us see each of these elements in detail:
Directives:
These affect the overall structure and behavior of a jsp.  There are three types of directives
  • Page: Usually specified at the beginning of page and affects the entire page. Examples are import, extends, session, info, isErrorPage, language, errorPage, autoFlush, contentType, buffer, isThreadSafe.
  • Syntax : <%@page attributename=”value”%>
e.g. <%@page  import=”java.lang.io”%>
  • Include: Include another file in this jsp. During translation phase of jsp, this file is included and complete jsp is prepared. This is a static include, the dynamic include is discussed later. In static include, the file is inserted in the jsp, while in dynamic include the request is forwarded to the included page to include execution response.
Syntax  : <%@include file=”filename”%>
e.g. <%@include file=”com.constants”%>
  • Taglib: This directive is used to make custom tag library use possible. In this directive, the prefix and uri are identified.
Syntax : <%taglib Uri=”path” prefix=”prefixToBeUsed”%> 
e.g. <%taglib Uri=”WEB-INF/mytaglib.tld” prefix=”mytaglib”%>
Scriptlets:
Scriptlets are the Java statements included in jsp. To differentiate these contents, the statements are included in <%…………%>. When the translation activity happens, these snippets are inserted in the jspService() method. As the service method is executed on each request, these snippets are also executed for each request. When you are using the jsp variables in these scriptlets, you need to keep this thing in mind that this code is executed at server side. Hence those variables needs to be available at the server side. Any mix up of client side variable in scriptlet will result in compilation problem or garbage value processing.
Actions:
Actions are taken when a request hits a jsp page. So, the actions are request processing instructions to the web/servlet container. Below are the jsp action examples with their use.
  • <jsp:include>: Dynamic inclusion of a page. The response of the included page is included in final response.
  • <jsp:forward>: Redirecting request to n different page. In include, the response is not committed, while here, the response is committed and a new request is sent.
  • <jsp:param>: Parameters to be passed inside include and forward tags to make available of the new jsp page through request object.
  • <jsp:useBean>: Integrating java beans with jsp page to transfer data through these beans and request objects.
  • <jsp:getProperty> and <jsp:setProperty>: Along with useBean, these are getter/setter methods of the attributes.
  • <jsp:plugin>: Browser will execute an applet or a bean based on this tag.
Expressions:
Evaluate the expression and send the value as a part of response to client. The expression inside this tag <%……%> is evaluated and just the result is sent back to the client as a string.
Comments:
Used to comment code in jsp. There are two options. First option tag used is <%– Comment –%>. This comment will be ignored by the web container and no code will be sent in response. That means comments are not transferred over network, and the amount of data sent over network is reduced. Second syntax is html comments <!-comment –>. Container treats it as an html and sends it to the client.
Declarations:
Using this, we can declare the class level variables, methods and classes. These declarations are initialized when the JSP is initialized. The scope of initialization is class level. Class level variable means the translation phase keeps these variables outside the service method at class level. Hence once set these attributes are available in each request to service method. The syntax used is -
<%! String name = “Jsp Tutorial”; %>
Template Text:
This is other than the jsp code. The fillers that are used sometimes to define the look and feel of the page presented. This code can be html, xml, wml or text.
<H1>ABC</H1>
To Summarize, above elements are to be used when we write a jsp page. There are different uses of each element. We need to use the correct element after understanding the response they will generate.

Implicit object are those objects which are available in jsp by default. Developer does not need to declare these objects, the web container creates them. What would be rational behind creation of such objects? Why would thecontainer create these objects? Can we not work without these objects? We will try to find answers to these questions in this article.
Web container executes the JSP page as a servlet. Servlet operates in request – response model. All objects, that are associated with any servlet by default, are part of this implicit object group. Each servlet has information related to the container’s environment, the servlet itself, the interaction session with user, definitely the request and response, etc. This information along with information related to the jsp page itself, is made available to the jsp via the implicit objects. The following is a list of jsp implicit objects:
  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception
Let us look at these objects in detail.
request:
  • Request object represents the request made by a client to the servlet.
  • This request is passed as an instance of javax.servlet.HttpServletRequest object.
  • This is an input parameter to the jspService() method.
  • Contains http header, request attributes, session etc.
response:
  • It represents the response generated by the servlet.
  • This is an instance of javax.servlet.HttpServletResponse class.
  • This is another input parameter to the jspService() method of the generated servlet.
pageContext:
  • Using this object, we can interact with the servlet container.
  • It is an instance of javax.servlet.jsp.PageContext class.
  • Container can manage page attributes like error pages, forwarding pages and including pages using this object.
session:
  • Represents the session between client and servlet (server).
  • Instance of HttpSession class.
  • Can be used to store attributes applicable to user session and not request.
application:
  • It is an instance of ServletContext class.
  • Used to share data amongst servlets, jsps and html pages in an application.
out:
  • This object is used to send output to the client.
  • It is an instance of javax.servlet.jsp.JspWriter class.
  • Based on the content type defined, the output will be generated.
  • Some of the methods available are print, println, flush, etc.
config:
  • This represents the servlet configuration.
  • It is an instance of javax.servlet.ServletConfig class.
page:
  • Represents the instance of generated servlet – “this”.
exception:
  • It is an instance of java.lang.Throwable class.
  • It encapsulates the exception thrown by the servlet.
  • If the jsp contains page directive for error page, then this exception is forwarded to that page.
To summarize, implicit objects are available in the jsp by default, and these objects can be used to serve a definite purpose which would otherwise be difficult.

A JSP works using http request – response model. Client browser sends a http request to the web container which is handled by the servlet from JSP. The request is executed by jspService() method and generated response is sent back. This transaction involves many data objects, which are used to encapsulate specific data. These objects may contain business data or environment data. It is important to define the extent of data sharing allowed by these objects. Defining scope of these object puts restriction on sharing of these objects in this request-response cycle. In addition to this, the request itself can be forwarded or redirected before generating final response. In this article, we will look as these request processing aspects. Following four main points are discussed in detail.
  • Scope
  • Include
  • Forward
  • Redirect
Scope:
Scope attribute defines the context in which any object will be available. Based on this availability information, we can use different objects. In a Jsp, there are following four scopes identified.
  • page: page maps to the jspService() method of generated servlet. Hence an object with page scope is available in service method only.
  • request: Request originates from a client browser and is executed in the jspService() method of generated servlet, to result in a response. Objects with this scope are available as long as the request object is available. These objects can be retrieved from the request object using getAttribute method.
  • session: This scope is larger than the request scope. Session scope lasts as long as the user session exists. Similar to request scope, these objects can also be retrieved using getAttribute method.
  • application: In this scope, the object is bound to ServletContext object. This scope is higher than the session scope and the object will get shared amongst different sessions of same user or sessions of different users. Here also ‘getAttribute’ method can be used to retrieve the object.
The scope goes on increasing in sequence from page, request, session to application.
Include:
Jsp components are included to increase reuse of code. We can include these components using either static include or using dynamic include. Static include is implemented using <%@include file=”filename”%> syntax. This include inserts the contents of included file in the jsp. Thus a new jsp is created after all inclusions. Requests are handled by the servlet generated from this new jsp. There is no other change in request-response model. Here the file can be html, jsp, image, etc.
Dynamic include is different from static include in many aspects. It is implemented using <jsp:include page=”filename”/> action element. While translating the jsp, container converts this include into a method call. During runtime, the method will be executed to render the page. This included page will have access to all implicit objects of the parent jsp. Only html and jsp pages can be included using this method.
Forward:
<jsp:forward page=”url”/> is used to forward request to another page. Target page will execute the request and send response to client. Attributes to be forwarded to target page can also be included in this tag.
Redirect:
In this scenario, the request will be redirected to a new resource. HttpServletResponse object’s sendRedirect() method is used to implement this. In redirect, the response of first request is returned to client browser and browser issues a new request all together.