JSP Implicit Objects.

JSP Implicit Objects

  • The javaserver pages (jsp) technology defines a number of implicit objects that scripting elements can use.
  • Each of these implicit objects are classes or interfaces as defined by either the Servlet or JSP specifications.

Implicit object: request

  • This is the most notable of the implicit objects and is an instance of the javax.servlet.http.ServletRequest interface.
  • The request object provides access to all the available information about the user request (such as request parameters and headers).
  • The request object can may be used in exactly the same way that the javax.servlet.http.HttpServletRequest parameter is used in the service() method of a servlet.
  • If any parameter is given to a page as a GET, PUT or POST type request you can print it out using the getParameter() method on the request object.
    Example:
    Hello <%= request.getParameter("userName")%>, Have a nice day!

Implicit object: response

  • The implicit response object represents the current response to be returned to the user and is a instance of the javax.servlet.http.HttpServletResponse interface.
  • The respone object can may be used in exactly the same way that the javax.servlet.http.HttpServletResponse parameter is used in the service() method of a servlet.

Implicit object: out

  • The implicit out object represents a instance of the javax.servlet.jsp.JspWriter class.
  • With this object you can write character data to the response stream in a similar manner to that seen by the java.io.PrintWriter class.
  • The out implicit object has many methods that you can use, but the most important is the methods print() and println(), which write to the body of the response.

Implicit object: session

  • The implicit session object provides a reference to an implementation of the client’s individual javax.servlet.http.HttpSession object.
  • You can store and retrieve session data on the this object.
  • Remember that several action elements that interact with the session are available and can be used instead.

Implicit object: config

  • The config object provides the JSP developer with access to the javax.servlet.ServletConfig object that is used by the web container to configure the JSP page.
  • The javax.servlet.ServletConfig interface is most commonly used to provide access to any initialization parameters that have been configured for the JSP page via the deployment descriptor of the web application.

Implicit object: application

  • The implicit application object provides a reference to the javax.servlet.ServletContext interface of the web application.
  • Several action elements exist that interact with the ServletContext so it may not be necessary to interact directly with the object itself.

Implicit object: page

  • The implicit page object references an instance of the JSP’s page implementation class and is declared of type Object.
  • The page object is rarely used in scripting elements and simply serves as a link between the JSP page and its implementing servlet.

Implicit object: pageContext

  • The pageContext object is slightly different in its functionality from the rest of the available implicit objects.
  • The pageContext variable provides this cross-scope functionality because it exists at a level of abstraction higher than the lower-level JSP implementation classes.
  • It provides the ability to search for named attributes across multiple scopes.

Implicit object: exception

  • The implicit exception object is available only to those JSP pages that declare themselves as error pages by using the following page directive.
    Example:
    <%@ page isErrorPage="true" %>

Example of using JSP implicit objects.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is JSPImplicitObjects).

JSP file to list Implicit objects data.

  • Here is the jsp-file that lists some of the possible data from some of the jsp implicit objects:
    <%@page contentType="text/html" pageEncoding="UTF-8" 
            errorPage="/WEB-INF/errorpage.jsp" import="java.util.*" %>
    <!DOCTYPE html >
    <html>
      <head>
        <meta http-equiv="Content-Type" 
              content="text/html; charset=UTF-8">
        <title>Library Book Control</title>
        <style>
          .gradientdown {
            background:  #e0e6ff;
            background: -webkit-linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
            background: -o-linear-gradient(#e0e6ff, #eeeeee); /* For Opera 11.1 to 12.0 */
            background: -moz-linear-gradient(top, #e0e6ff, #eeeeee); /* For Firefox 3.6 to 15 */
            background: linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* W3C Standard syntax (must be last) */
          }
          table tr.data:nth-of-type(odd) { 
            background: #eeeeee; 
          }
          table {
            width: 100%; table-layout: fixed;
          }
        </style>  
    
      </head>
      <body onload="submitForm();">
        <div style="max-width:500px; ">
          <%
           String str= request.getParameter("error");
           if (str!=null){
             int x= 200/0;
           }
            // this is only for demo
            session.setAttribute("sessiondata",
                    new Object() {
                      public String toString() {
                        return "This is the session data";
                      }
                    });
            request.setAttribute("time",
                    (new java.util.Date()).toString());
          %> 
          <h2>Implicit object info:</h2>  
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Request object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getContextPath()%></td> 
              <td>getContextPath()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getMethod()%></td> 
              <td>getMethod()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getRequestURI()%></td> 
              <td>getPathInfo()</td> 
            </tr>
            <tr class="data" style="word-wrap: break-word;">
              <td><%= request.getQueryString()%></td> 
              <td>getQueryString()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= (String) request.getAttribute("time")%></td> 
              <td>getAttribute("time")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getParameter("isbn_no")%></td> 
              <td>getParameter("isbn_no")</td> 
            </tr>  
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getParameter("short_desc")%></td> 
              <td>getParameter("short_desc")</td> 
            </tr>  
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getParameter("price")%></td> 
              <td>getParameter("isbn_no")</td> 
            </tr>  
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getParameter("action")%></td> 
              <td>getParameter("action")</td> 
            </tr>  
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getServletContext().getServerInfo()%></td> 
              <td>getServletContext().getServerInfo()</td> 
            </tr>  
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= request.getServletContext().getInitParameter("welcome")%></td> 
              <td>getServletContext(). getInitParameter("welcome")</td> 
            </tr>  
          </table>
          <hr>
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Session object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%=  session.getServletContext().getInitParameter("welcome")%></td> 
              <td>getServletContext(). getInitParameter("welcome")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= (new java.util.Date(session.getCreationTime())).toString()%></td> 
              <td>getCreationTime()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= (new java.util.Date(session.getLastAccessedTime())).toString()%></td> 
              <td>getLastAccessedTime()</td> 
            </tr>
            <tr class="data" style="word-wrap: break-word;">
              <td><%= session.getId()%></td> 
              <td>getId()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= session.isNew() ? "New" : "Not new"%></td> 
              <td>isNew()?"New":"Not new"</td> 
            </tr>
          </table>    
          <hr>
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Out object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><% out.println("this is only a test");%></td> 
              <td>println("this is only a test");</td> 
            </tr>
          </table>    
          <hr>
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Session object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= session.getServletContext().getInitParameter("welcome")%></td> 
              <td>getServletContext(). getInitParameter("welcome")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= session.getAttribute("sessiondata")%></td> 
              <td>getAttribute("sessiondata")</td> 
            </tr>
          </table>  
          <hr>    
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Config object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= config.getServletName()%></td> 
              <td>getServletName()</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= config.getInitParameter("initParam")%></td> 
              <td>getInitParameter("initParam")</td> 
            </tr>  
          </table> 
          <hr>      
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Application object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= application.getInitParameter("welcome") %></td> 
              <td>getInitParameter("welcome")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= application.getRealPath("/") %></td> 
              <td>getRealPath("/")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= application.getVirtualServerName() %></td> 
              <td>getVirtualServerName()</td> 
            </tr>
          </table> 
          <hr>      
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">PageContext object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= pageContext.findAttribute("sessiondata") %></td> 
              <td>findAttribute("sessiondata")</td> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td><%= pageContext.findAttribute("time") %></td> 
              <td>findAttribute("time")</td> 
            </tr>     
          </table> 
          <hr>      
          <table style="width:100%;" >
            <tr class="gradientdown">
              <th style="width:50%;">Result</th> 
              <th style="width:50%;">Exception object method(s)</th> 
            </tr>
            <tr class="data"  style="word-wrap: break-word;">
              <td>Select the link</td> 
              <td><a href="index.jsp?error=doit" >causing errors</a></td> 
            </tr>
         
          </table> 
          <hr>      
        </div>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Request.jsp).

  • In this file, we expect some request parameters from a html form and an attribute on the request as well.
  • For this demonstration, we have also created an attribute on the session object.
  • To see the result of using an error page, we have created an error request parameter that causes division by 0.
  • The error page must be given as an attribute to the page directive.

We need to create an error page.

  • <%@ page isErrorPage="true" %>
    <html>
    <head>
      <title>Display the Exception Message here</title>
    </head>
    <body>
       <h2>errorpage.jsp</h2>
       <p>An exception has occurred in the index.jsp Page.</p>
       <p>Please fix the errors.</p>
       Below is the error message:</p>
       <b><%= exception %></b>
       <p>Please go to the <a href="Startup.jsp">Startup Page</a>.</p>
    </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

  • In this errorpage JSP file we must specify with an attriute to the page directive that this is an errorpage. It is common to put these files in WEB-INF.

I like to start up with a JSP file (s) which pass request data to the index.jsp file.

  • <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script language="JavaScript">
          function submitForm() {
            document.getElementById('newBook').submit();
          }
        </script>    
      </head>
      <body onload="submitForm();">
        <form id="newBook" action='index.jsp' method="GET">
          <input type="hidden" name="isbn_no"  value="0201703092"   />
          <input type="hidden" name="short_desc" value="The Practical SQL" />
          <input type="hidden" name="price" value="39" />
          <input type="hidden" name="action" value="add"/>
        </form>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Startup).

  • When the file is loaded we simulate a submit of form input data to the index.jsp file.

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee     
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
      <servlet>
        <servlet-name>Startup</servlet-name>
        <jsp-file>/Startup.jsp</jsp-file>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet>
        <servlet-name>index</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
        <init-param>
          <param-name>initParam</param-name>
          <param-value>index.jsp init param</param-value>
        </init-param>
      </servlet>
      <servlet-mapping>
        <servlet-name>Startup</servlet-name>
        <url-pattern>/Startup</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>index</servlet-name>
        <url-pattern>/index.jsp</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>Startup</welcome-file>
      </welcome-file-list>
      <context-param>
        <param-name>welcome</param-name>
        <param-value>Welcome text</param-value>
      </context-param>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • For each servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • For the index.jsp we have registered a <param-name> tag to demonstrate use of servlet initial data.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url Startup. Reorganize the welcome-file-list to what is shown above.
  • At the end of the file we have registered a <param-name> tag to demonstrate use of application initial data.

Creating Web-server Deployment descriptor.

  • The context-root (in example /JSPImplicitObjects) for the application will in most cases be specified by a server vendor deployment descriptor.
    The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.