JSP lifecycle phases

  1. Translation of JSP to Servlet code.
  2. Compilation of Servlet to bytecode.
  3. Loading Servlet class.
  4. Creating servlet instance.
  5. Initialization by calling jspInit() method
  6. Request Processing by calling _jspService() method
  7. Destroying by calling jspDestroy() method

JSP lifecycle methods

  1. jspInit() method-What is jspInit() method
    Once a JSP file is successfully compiled into a class file, jsp engine calls jspInit() method to initialize class file. This method is called by the container only once during the lifecycle. jspInit() method can be overridden by the author to initialize resources such as database and network related connections.

    public void jspInit() {
      // initialization code or something needs to be called before JSP page
      // starts serving the requests.
     }
    

    Now the question arises why we shouldn’t use constructor instead of init method of jsp or servlet ?. Of course ! we can use constructor instead of init() method, there is nothing to stop us. In previous versions of java it was not possible to dynamically call constructor with arguments. This does no longer applied, but servlet containers still looks for an no-argument constructor. So we won’t have access to a ServletConfig or ServletContext if we use constructor instead of init() method.

  2. _jspService() method – _jspService() method is called every time a request comes to jsp during its lifecycle. The (_) underscore sign indicates that this method is generated by Container and hence cannot be overriden. The jsp code written by us goes in _jspService() because this is implicitly implemented. In case we tries to override it explicitly, JSP compliler will give an error saying “the method is already implemented and cannot override’.
  3. jspDestroy() method
    jspDestroy() method is called when servlet(jsp) is no longer in use, with the call of this method jsp lifecycle is ended and jsp submits itself to garbage collection.

    public void jspDestroy() {
      // code related to release resources like database ot network
      // connections.
     }
    

    We can always call jspDestroy() at any stage of its lifecycle but it does not make sense because even if you called jspDestroy() in the beginning, it doesn’t stops the JSP to execute the _jspService() method and sending the response back to the client. This is one of the lifecycle method which is invoked by the JSP Container when the jsp instance is removed.

Implicit objects in JSP – Objects created by web container and contain information regarding a particular request, application or page are called Implicit Objects.

Implicit object is the object that is created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

  1. response
  2. request
  3. exception
  4. application
  5. session
  6. pageContext
  7. page
  8. config
  9. out

Is JSP technology extensible?
Yes, JSP is easily extensible by use and modification of tags, or custom actions, encapsulated in tag libraries.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
requestDispatcher – forward() method

  1. When we use forward method, request is transfer to other resource within the same server for further processing.
  2. In case of forward, web container handle all process internally and client or browser is not involved.
  3. When forward is called on requestdispatcher object we pass request and response objects so our old request object is present on new resource which is going to process our request.
  4. Visually we are not able to see the forwarded address, it is transparent.
  5. Using forward () method is faster then send redirect.
  6. When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.

HttpServletResponse.sendRedirect() method

  1. In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.
  2. When you use sendRedirect, container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
  3. In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.
  4. In address bar, we are able to see the new redirected address. It’s not transparent.
  5. sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.
  6. But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.

Which one is good?
If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect. Generally, forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

How HttpServletResponse.sendRedirect() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with Location: other.jsp header
  3. Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  4. Server sends a HTTP response back with content of other.jsp.

How RequestDispatcher.forward() Works

  1. Client sends a HTTP request to some.jsp.
  2. Server sends a HTTP response back with content of other.jsp.

How can a thread safe JSP page be implemented?
It can be done by having them implemented by the SingleThreadModel Interface. Add <%@page isThreadSafe=”false” %> directive in the JSP page.

How do I prevent the output of my JSP or Servlet pages from being cached?

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

How do we configure init params for JSP?
We can configure init params for JSP similar to servlet in web.xml file, we need to configure JSP init params with servlet and servlet-mapping element.

What is Scriptlet, Expression and Declaration in JSP?

A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the _jspService() method. For example;

<%
Date d = new Date();
System.out.println("Current Date="+d);
%>

Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.

<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as

<%! public static int count=0; %>

Use of pageContext Object

  1. pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.This object is intended as a means to access information about the page while avoiding most of the implementation details.
  2. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
  3. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
  4. important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute (“attrName”) removes the attribute from all scopes, while the following code only removes it from the page scope
pageContext.removeAttribute("attrName", PAGE_SCOPE);

Other Example

ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

JSP Action Elements or Action Tags
JSP action elements or action tags are HTML like tags that provide useful functionalities such as working with Java Bean, including a resource, forwarding the request and to generate dynamic XML elements. JSP action elements always starts with jsp: and we can use them in JSP page directly without the need to import any tag libraries or any other configuration changes. Some of the important action elements are jsp:useBean, jsp:getProperty, jsp:setProperty, jsp:include and jsp:forward.

Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element’s attribute.
jsp:body Defines dynamically defined XML element’s body.
jsp:text Use to write template text in JSP pages and documents.

difference between include directive and jsp:include action?
The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.

Another difference is that in JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.

When included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.

What are JSP EL implicit objects and how it’s different from JSP implicit Objects?
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. Note that these are different from JSP implicit objects and contains only the attributes in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.

JSP EL Implicit Objects Type Description
pageScope Map A map that contains the attributes set with page scope.
requestScope Map Used to get the attribute value with request scope.
sessionScope Map Used to get the attribute value with session scope.
applicationScope Map Used to get the attributes value from application scope.
param Map Used to get the request parameter value, returns a single value
paramValues Map Used to get the request param values in an array, useful when request parameter contain multiple values.
header Map Used to get request header information.
headerValues Map Used to get header values in an array.
cookie Map Used to get the cookie value in the JSP
initParam Map Used to get the context init params, we can’t use it for servlet init params

What is JSP Standard Tag Library, provide some example usage?
JSP Standard Tag Library or JSTL is more versatile than JSP EL or Action elements because we can loop through a collection or escape HTML tags to show them like text in response.JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container.

What is difference between JspWriter and Servlet PrintWriter?
PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.

<%@ include is a static include, The include directive:

<%@ include file="header.html" %>

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

standard action:

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like , but it’s more powerful and flexible: unlike the other two includes, the url can be from outside the web Container!

Preludes and codas:
Static preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding and elements respectively within a element in the Web application web.xml deployment descriptor.

How can one Jsp Communicate with Java file.

<%@ page import="market.stock.*” %>

What is web.xml
The /WEB-INF/web.xml file is the Web Application Deployment Descriptor of your application. This file is an XML document that defines everything about your application that a server needs to know except the context path.

whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded.

Defining like this 1 is also known as pre-initialization of servlet means now the servlet for which we have defined this tag has been initialized in starting when context is loaded before getting any request.

Comments are closed.