JSP Implicit Objects

Filed Under: Java EE

JSP Implicit Objects are very useful for developers. This is the second post in the series of JSP Tutorials, you might want to check out earlier post about JSP Tutorial for Beginners.

JSP Implicit Objects

Implicit Objects in JSP

JSP implicit objects are created by servlet container while translating JSP page to Servlet source to help developers. We can use implicit objects in JSP directly in scriptlets that goes in service method. However we can’t use jsp implicit objects in JSP declaration because that code will go at class level.

We have 9 jsp implicit objects that we can directly use in JSP page. Seven of them are declared as local variable at the start of _jspService() method whereas two of them are part of _jspService() method argument that we can use.

  1. JSP Implicit Objects – out Object
  2. JSP Implicit Objects – request Object
  3. JSP Implicit Objects – response Object
  4. JSP Implicit Objects – config Object
  5. JSP Implicit Objects – application Object
  6. JSP Implicit Objects – session Object
  7. JSP Implicit Objects – pageContext Object
  8. JSP Implicit Objects – page Object
  9. JSP Implicit Objects – exception Object
  10. JSP Implicit Objects Example

Implicit Objects in JSP

Let’s look into each of the implicit objects in JSP page one by one. Then we will go through JSP implicit objects example.

  1. JSP Implicit Objects – out Object

    JSP out implicit object is instance of javax.servlet.jsp.JspWriter implementation and it’s used to output content to be sent in client response. This is one of the most used JSP implicit object and thats why we have JSP Expression to easily invoke out.print() method.

  2. JSP Implicit Objects – request Object

    JSP request implicit object is instance of javax.servlet.http.HttpServletRequest implementation and it’s one of the argument of JSP service method. We can use request object to get the request parameters, cookies, request attributes, session, header information and other details about client request.

  3. JSP Implicit Objects – response Object

    JSP response implicit object is instance of javax.servlet.http.HttpServletResponse implementation and comes as argument of service method. We can response object to set content type, character encoding, header information in response, adding cookies to response and redirecting the request to other resource.

  4. JSP Implicit Objects – config Object

    JSP config implicit object is instance of javax.servlet.ServletConfig implementation and used to get the JSP init params configured in deployment descriptor.

  5. JSP Implicit Objects – application Object

    JSP application implicit object is instance of javax.servlet.ServletContext implementation and it’s used to get the context information and attributes in JSP. We can use it to get the RequestDispatcher object in JSP to forward the request to another resource or to include the response from another resource in the JSP.

  6. JSP Implicit Objects – session Object

    JSP session implicit object is instance of javax.servlet.http.HttpSession implementation. Whenever we request a JSP page, container automatically creates a session for the JSP in the service method.

    Since session management is heavy process, so if we don’t want session to be created for JSP, we can use page directive to not create the session for JSP using <%@ page session="false" %>. This is very helpful when our login page or the index page is a JSP page and we don’t need any user session there.

  7. JSP Implicit Objects – pageContext Object

    JSP pageContext implicit object is instance of javax.servlet.jsp.PageContext abstract class implementation. We can use pageContext to get and set attributes with different scopes and to forward request to other resources. pageContext object also hold reference to other implicit object.

  8. JSP Implicit Objects – page Object

    JSP page implicit object is instance of java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.

  9. JSP Implicit Objects – exception Object

    JSP exception implicit object is instance of java.lang.Throwable class and used to provide exception details in JSP error pages. We can’t use this object in normal JSP pages and it’s available only in JSP error pages.

JSP Implicit Objects Example

Here is a simple JSP page that’s showing usage of JSP implicit objects. I am not providing exception object example, that will be covered in JSP Exception Handling post.

index.jsp


<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ page import="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Index JSP Page</title>
</head>
<body>
<%-- out object example --%>
<h4>Hi There</h4>
<strong>Current Time is</strong>: <% out.print(new Date()); %><br><br>

<%-- request object example --%>
<strong>Request User-Agent</strong>: <%=request.getHeader("User-Agent") %><br><br>

<%-- response object example --%>
<%response.addCookie(new Cookie("Test","Value")); %>

<%-- config object example --%>
<strong>User init param value</strong>:<%=config.getInitParameter("User") %><br><br>

<%-- application object example --%>
<strong>User context param value</strong>:<%=application.getInitParameter("User") %><br><br>

<%-- session object example --%>
<strong>User Session ID</strong>:<%=session.getId() %><br><br>

<%-- pageContext object example --%>
<% pageContext.setAttribute("Test", "Test Value"); %>
<strong>PageContext attribute</strong>: {Name="Test",Value="<%=pageContext.getAttribute("Test") %>"}<br><br>

<%-- page object example --%>
<strong>Generated Servlet Name</strong>:<%=page.getClass().getName() %>

</body>
</html>

Deployment descriptor for the dynamic web project is:

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>JSPImplicitObjects</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <context-param>
  <param-name>User</param-name>
  <param-value>Admin</param-value>
  </context-param>
  
  <servlet>
  <servlet-name>home</servlet-name>
  <jsp-file>/index.jsp</jsp-file>
  <init-param>
  	<param-name>User</param-name>
  	<param-value>Pankaj</param-value>
  </init-param>
  </servlet>
  <servlet-mapping>
  <servlet-name>home</servlet-name>
  <url-pattern>/home.do</url-pattern>
  <url-pattern>/home.jsp</url-pattern>
  </servlet-mapping>
</web-app>

When I access above JSP in browser, I get response like below image.

JSP Implicit Objects

Let’s look at the generated servlet class code for better understanding about these objects.

index_jsp.java


/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.32
 * Generated at: 2013-08-22 00:42:24 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.*;
import java.util.Date;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  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; charset=US-ASCII");
      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("\n");
      out.write("\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=US-ASCII\">\n");
      out.write("<title>Index JSP Page</title>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      out.write("\n");
      out.write("<h4>Hi There</h4>\n");
      out.write("<strong>Current Time is</strong>: ");
 out.print(new Date()); 
      out.write("<br><br>\n");
      out.write("\n");
      out.write("\n");
      out.write("<strong>Request User-Agent</strong>: ");
      out.print(request.getHeader("User-Agent") );
      out.write("<br><br>\n");
      out.write("\n");
      out.write('\n');
response.addCookie(new Cookie("Test","Value")); 
      out.write('\n');
      out.write('\n');
      out.write("\n");
      out.write("<strong>User init param value</strong>:");
      out.print(config.getInitParameter("User") );
      out.write("<br><br>\n");
      out.write("\n");
      out.write("\n");
      out.write("<strong>User context param value</strong>:");
      out.print(application.getInitParameter("User") );
      out.write("<br><br>\n");
      out.write("\n");
      out.write("\n");
      out.write("<strong>User Session ID</strong>:");
      out.print(session.getId() );
      out.write("<br><br>\n");
      out.write("\n");
      out.write('\n');
 pageContext.setAttribute("Test", "Test Value"); 
      out.write("\n");
      out.write("<strong>PageContext attribute</strong>: {Name=\"Test\",Value=\"");
      out.print(pageContext.getAttribute("Test") );
      out.write("\"}<br><br>\n");
      out.write("\n");
      out.write("\n");
      out.write("<strong>Generated Servlet Name</strong>:");
      out.print(page.getClass().getName() );
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("</body>\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);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

Thats all for JSP implicit objects, in future posts you will see a lot of examples where they will be used.

Comments

  1. Vishal Patil says:

    why there is no need to create object of implicit objects in jsp but in servlet we need to create object?

  2. Bob Craver says:

    When you add a cookie in a Servlet in the doPost method for example something like this: response.addCookie(cookie) and then you redirect to another JSP. How come that JSP you redirect to has access to the cookie object you created in the servlet? Since you only added it to the response. There is no method from the ServletResponse to getCookie() or something…

  3. Mahesh says:

    Hi sir

    your tutorials are very useful for us…….

  4. Satvik says:

    I am Getting

    HTTP Status 500 – java.lang.NullPointerException

    type Exception report

    message java.lang.NullPointerException

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:538)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    root cause

    java.lang.NullPointerException
    org.apache.jsp.WEB_002dINF.index_jsp._jspInit(index_jsp.java:23)
    org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:52)
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:164)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:340)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.44 logs.

  5. Venkata Sailendra says:

    Dear sir ,

    Thank you so much for your posts.
    I am trying to get a job and I learnt all the concepts through your sites.
    I am sure I can get a job in 2 months and will send you a gift as soon as I get.

    Thanks again

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages