05 - JSP Page Life Cycle: Page 3 of 3

5.3 JSP life cycle Example

In this section, we will write one JSP file to demonstrate the JSP life cycle phases discussed above. Lets write one jsp file which will display the visitor number. Initialization block is used to initialize it with 0 and destroy is used to reset counter to 0 .

<html>
    <head>
        <title> JSP life cycle demonstration </title>
    </head>
    <body>
<%!
// define a instance variable by defining it in a declaration tag
int visitorCounter ;
// override jspInit() method
public void jspInit()
{
/*
initialize counter by dummy value say 0. Ideally this should be grabbed
from some data source but for the sake of example I am  hardcoding it
*/
visitorCounter=0;
}
// override destroy method which will set the value of counter back to 0
public void jspDestroy()
{
visitorCounter=0;
}
%>
<%
/*
increment the counter on each visit using scriplet. All code written inside scriplet goes under service()
 so will be executed on each request
*/
visitorCounter = visitorCounter+1;
%>
        <strong>
Thanks for visiting the page. You are <%=visitorCounter %> visitor of the page.
        </strong>
    </body>
</html>

Below is the generated Java class of above jsp file ( generated inside work/catalina/localhost / <<your web application>> / org/apache/jsp of tomcat installation directory)

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.27
 * Generated at: 2014-10-04 19:30:11 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class visitorsCounter_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent
{
// define a instance variable by defining it in a declaration tag
int visitorCounter ;
// override jspInit() method
public void jspInit()
{
/*
initialize counter by dummy value say 0. Ideally this should be grabbed
from some data source but for the sake of example I am  hardcoding it
*/
visitorCounter=0;
}
// override destroy method which will set the value of counter back to 0
public void jspDestroy()
{
visitorCounter=0;
}
  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();
  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;
  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }
  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }
  public void _jspDestroy() {
  }
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;
    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
       null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<title> JSP life cycle demonstration </title>\r\n");
      out.write("</head>\r\n");
      out.write("\r\n");
      out.write("<body>\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
/*
increment the counter on each visit using scriplet. All code written inside scriplet goes under service()
 so will be executed on each request
*/
visitorCounter = visitorCounter+1;
      out.write("\r\n");
      out.write("\t\r\n");
      out.write("<strong> \r\n");
      out.write("\tThanks for visiting the page. You are ");
      out.print(visitorCounter );
      out.write(" visitor of the page. \r\n");
      out.write("</strong>\t\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

If you look at the highlighted section ( in red) in generated code , this is rthe _jspService() method which we did not define in a jsp file but gets added by container .Also all the code written inside scriplets goes inside it and all html code is added within println statements

On hitting the jsp page we can see counter value gets increased on every hit.

 

 

5.4 JSP Pre-Compilation

Usually the jsp page is translated to servlet when it is invoked for the first time which means developer will come to know about such errors while he hits the page. This is very time consuming specially in the development phase.

JSP specification provides a way (using jsp_precompile) which forces jsp to compile without actually executing it.

The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.

For example if I want to pre compile test.jsp file I need to hit

http://localhost:8080/jsp-tutorial/test.jsp?jsp_precompile=true

Valid values of jsp_precompile query parameter is true or false with default value as true so above statement is equivalent to

http://localhost:8080/jsp-tutorial/test.jsp?jsp_precompile

Passing value as false means no pre compilation but in both cases jsp page execution will not happen.

jsp_precompile is possible on one jsp at a time and if you have a bunch of files that you want to pre compile , there is no direct way of it.

There are several advantages of pre compilation of jsp file and couple of them are -

· If the jsp file is pre compiled , which means JSP engine need not to perform entire translation activity upon receipt of the and hence it removes the start-up lag that occurs upon receipt of the first request.

· During development phase, developers can use this feature to test the code and they need not to run a complete flow to test the changes.

If you are wondering that even with pre compilation developers have to hit the jsp so where is the difference then think of the scenarios where a jsp is displayed after performing several transactions or activities or displayed conditionally based on result of some parameters. With this approach , developers need not to run complete flow every time to verify the changes and can directly hit the jsp page.

Like us on Facebook