Implicit Objects & Actions  
 Peter Komisar              v.2.2 ©                      
Conestoga College

reference: JavaServer PagesTM Fundamentals Short Course,Govind Seshadri
 http://developer.java.sun.com/servlet/PrintPageServlet, The J2EE Tutorial,
Java Server Pages, Stephanie Brodoff, Java ServerPages 1.2 Syntax Card,
http://java.sun.com/products/jsp/pdf/card12.pdf, Developing JSP Custom Tags,
http://developer.java.sun.com/developer/technicalArticles/xml/WebAppDev3/,

Qusay H. Mahmoud, 'Web Development with Java Server Pages'


Implicit Objects and Context Methods Supplied by
PageContext

The JSP container makes available a set of subclasses
called 'implicit objects'. They are special because you just
use them without having to take any creational steps. The
servlet engine makes these objects available to the page
writer, via an intermediary class called PageContext. 

PageContext is not often seen. It is mainly used 'behind the
scenes' in processing JSP pages. The class is used to supply
references to the the various underlying facilities of the servlet
environment. These references or 'implicit objects' are used
inside scriptlets and expressions.

Following is a listing of the implicit objects with brief descriptions.
Also listed are Java classes that they represent. We discuss
scope further on in the note.
 

JSP Pages Implicit Objects
 
 Implicit Objects   Subclass Type  Description  Scope
 request   ServletRequest
 // javax.servlet
 the HttpServletRequest
 that
triggers the service call
 Request
 response  ServletResponse 
 // javax.servlet
 the HttpServletResponse
 to
the request.
 Page
 pageContext  PageContext
 // javax.servlet.jsp
 contains implementation-
 dependent features.
 Page
 session   HttpSession
 // javax.servlet.http
 An HttpSession object  Session
 application  ServletContext
 // javax.servlet
 the ServletContext in which 
 the servlet is running
 Session
 out  JspWriter
 // javax.servlet.jsp
 a JspWriter object that
writes
into the output stream
 Application
 config   ServletConfig
 // javax.servlet
 the ServletConfig  for the  JSP.   Page
 page  Object 
 // java.lang
 this, the HttpJspPage.  Page
 exception  Throwable
 // java.lang
 results in an error page invocation  Page


Now lets look briefly at the PageContext class that acts as a
bridge between the Java world of Servlets and the HTML world
of the Java Server Page.


PageContext Overview



The 'pageContext' Implicit Object

// handle to the PageContext Class

The abstract PageContext is extended by the JSP engine.
It is used to supply different types of services for the JSP
servlet. Following is a summary from the J2EE documentation
that describes it's features.


J2EE documentation Summary of the PageContext Facilities


PageContext Class Description   // paraphrased from the j2sdkee docs

A PageContext instance provides access to all the namespaces
that may be associated with a JSP page. Implicit objects are
added to the pageContext object automatically and are made
available by the following set of methods.

The PageContext does not of course get itself. It is available
from the JspFactory class via the getPageContext( ) method.
It is released using the JspFactory releasePageContext( )
method.  While the developer can use these methods it is
often easiest to use the implicit object, 'pageContext'.


JSP Scopes   

There are four implicit objects that can store attributes
each which have static constants associated with them.

Object that can Store Attributes:


Because there is a span of time associated with the persistence
of these attributes the same names are also used to describe
'scopes' which refer to the domains that each of these objects
exist in. The following table lists the constants found in the
PageContext class that represent the different scopes.


Scope Constants Found in the PageContext Class

 Scope
 Accessibility Description
public static final int APPLICATION_SCOPE - until the ServletContext object is reclaimed
public static final int SESSION_SCOPE - attributes of the HttpSession object of the
  the servlet; until the servlet is invalidated.
public static final int PAGE_SCOPE - attributes accessible in this PageContext
object until the current servlet service( ) 
 method returns
 public static final int
 REQUEST_SCOPE
 a named reference remains available from
 the ServletRequest associated with the
 Servlet until the current request is completed.


Application Scope

Application scope parallels the life of the ServletContext object.
This scope may last as long as the application keeps the page
loaded in memory potentially for the duration of the web application.


Session Scope

Session scope is associated with the life span of the session object
stored for as long a user is interacting with a web server.

Page Scope

Page scope is like 'this' and refers to the page itself. Page scope
is the default
scope. Page scope remains active while service( )
method of the page servlet is in process.

Request scope

Request scope is associated with the life of the request object.
While this might be a very brief time, it may be extended in the
event that the request is forwarded to another page.
A request
scope is available from the
ServletRequest object and lasts
until the current request is completed.


PageContext Methods Intended for JSP authors

Aside from the set of methods that retrieve the class instances
that correspond to the implicit objects, a set of PageContext
methods are devoted to manipulating the attributes of the
different available objects. These methods are summarized
below.

The setAttribute methods provide a default form that sets
attributes in the page context, or a second form that allows
setting the attribute in a specific scope. The set and remove
methods return void while the get methods return object type.

PageContext Attribute Manipulation Methods


Example
  

<%@  page import="javax.servlet.jsp.PageContext" %>
<%   pageContext.setAttribute("name","Bill", PageContext.SESSION_SCOPE); %>


Methods for Forwarding and Inclusion

PageContext also supply methods for forwarding and including.
These the programmatic equivalents of the actions <jsp:forward>
and <jsp:include>, which we cover in the next section.



Other Implicit Objects


The 'exception' Object

The exception object would usually come in near the last
of the list but we use it to demonstrate the fact that these
objects are 'just there' for you to use. The following scriptlet
shows how easy this and other implicit objects are to use.
Both the 'exception and the 'out' implicit object are shown
in use in the following example.

<%@  page isErrorPage="true" %>
<H1> HOUSTON! </H1>
The following Exception has been thrown.
<BR><BR/>
<%= exception %>
<% exception.printStackTrace( java.ioPrintWriter(out)) %>

// D.Fields et.al, in 'Web Development with JSPs' show redirecting
// the printStackTrace output to a new PrintWriter
instance which
// is then streamed to the implicit 'out' object

 

The 'page' Object

The page object represents the page servlet that the JSP
is translated into. This is an instance of
javax.servlet.Servlet.
The page object reference is the equivalent of the Java 'this'
reference.  The page object is rarely referenced in a page.

'Web Development in JSP" Example   // D.Fields et.al

<%@  page info = "Page implicit object demonstration ."   %>
Page info:
<%= ( ( javax.servlet.jsp.HttpJspPage)page).getServletInfo( ) %>

// the page implicit object has been cast to the superclass
// type by it's authors and it's getServletInfo( ) method is called



The 'config' Object
 
The 'config' object is a built in reference to the ServletConfig
class for the page servlet. The 'config' object can be used to
supply initialization parameters that have been entered into
a web application's deployment descriptor, eliminating the
need for exposing data in the JSP page code.

Example    

<%=  config.getInitParameter("version")  %>


The 'request' Object

The request object encapsulates the request that was
sent to retrieve the current page servlet. If the request
is wrapped in a HTTPRequest object, then all the
associated request header information is available
via this object. We can look at Apache's own servlet
examples to demonstrate the methods that the
HTTPServletRequest object supplies.

We could call all the same methods on the equivalent
'implicit' object inside a scriptlet of a JSP page.The
following Apache example code is actually two servlets
merged into one, combining both demonstrations of
the request object's methods.


Request Code From Two Apache Servlets 

// requests methods from two sample Apache servlets merged

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestHeaderEx2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter( );

out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Request Headers</title>");
out.println("</head>");
out.println("<body>");

// ***************************************************
// First Apache servlet example
// ***************************************************

Enumeration e = request.getHeaderNames( );
out.println("<H3>Servlet 1 Output: Headers as an enumeration</H3><HR/>");
while (e.hasMoreElements( )) {
String name = (String)e.nextElement( );
String value = request.getHeader(name);
out.println(name + " = " + value);
}

out.println("<HR/><H3> Servlet 2: Request HTTP MetaData methods</H3></HR>");


// ****************************************************************
// relevant methods from second Apache servlet example
// ****************************************************************

out.println("<BR/><B>Request URI:</B> " + request.getRequestURI( ));
out.println("<BR/><B>Protocol:</B> " + request.getProtocol( ));
out.println("<BR/><B>PathInfo:</B> " + request.getPathInfo( ));
out.println("<BR/><B>Remote Address:</B> " + request.getRemoteAddr( ));
out.println("</body>");
out.println("</html>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}


public String getRequestURI() 
  Returns the part of this request's URL from the protocol name
 up to the query string in the first line of the HTTP request. The
 web container does not decode this String. For example: 

First line of HTTP request Returned Value
POST /some/path.html HTTP/1.1
/some/path.html
GET http://foo.bar/a.html HTTP/1.0
/a.html
HEAD /xyz?a=b HTTP/1.1
/xyz


The response Object

The response is the object that is used to encapsulate
the response to a client request. If the response is an
HTTP response the object will be an implementation of
the javax.servlet.http.HttpServletResponse to show it
by it's fully qualified class name.

Inherited from the ServletResponse class is the method
setContentType( ) and setContentLength( ). ServletResponse
also provides methods such as get and setBufferSize( ),
flushBuffer( ), and set and getCharacterEncoding( ).

Defined in HttpServletResponse are methods to set
HTTP response headers. The following is a partial list.

To be used in conjunction with the following methods the
HTTPServletResponse object defines a long list of status
code constants. representing different error and non-error
conditions. The following examples show a few of the more
famous ones.

// HTTPServletResponse class documentation in J2EE docs


Example

public static final int SC_OK 
 // Status code (200) - indicates request succeeded normally.
public static final int  SC_NOT_FOUND
 // S.C(404) - indicates requested resource is not found


These constants hold the actual values used in the HTTP
protocol. The following code sample demonstrates that
the value held for the 'Page Not Found' error status code
is indeed the number 404.

Code Sample

import javax.servlet.http.*;

class Encode{
public static void main(String[]args){
System.out.println("Print SC_NOT_FOUND int value: "
+ HttpServletResponse.SC_NOT_FOUND);
}
}

Output
C:\JSP\Java>java Encode
Print SC_NOT_FOUND int value: 404

HTTPServletResponse also defines the methods used
in directing responses. The setStatus( ) method is used
in non-error conditions.


// reference from API: sendError( ) The server defaults to creating the
// response to look like an HTML-formatted server error page containing
// the specified message, setting the content type to "text/html", leaving
// cookies and other headers unmodified.



The 'out' Object

The 'out' object represents the page output stream. Out is
an instance of JSPWriter which in turn is an abstract class
that extends java.io.Writer from Java's io package. ( The
JSP container supplies an implementation for the abstract
JSPWriter.) 

JSPWriter inherits PrintWriter's standard write methods as
well as print( ) and println( ). JSPWriter also has methods
that manipulate the buffer such as getBufferSize( ),
getRemaining( ), clearBuffer(  ) and flush(  ).

It also has the standard stream method, close(  ). 


Example 
     

<%  int totalBytes = out.getBufferSize( ) ;
       int availableBytes = out.getRemaining( );  %>
         

Session Management With the 'sesssion' Object 

Sessions are important because they can allow state to
be maintained across a users transactions with a server.
A HTTPSession object provides a mechanism to identify
a user across more than one page request or visit to a
Web site. It also allows the server to store information
about that user.    // state


Sessions also provide a storage area that can be 'listened'
to by listeners to confirm a user is authenticated and logged
in. As well, the session object can store beans that represent
storage items like shopping carts. Session objects can be
shared by a number of cooperating servlets and JSP pages.

// storage items. listen for being logged in etc.

We know now that JSP pages by default participate in HTTP
sessions. The HTTPSession object is available through the
'session' implicit object. The session ID is identified by a
session ID which can be stored in the browser as a cookie.

// a session can be maintained using cookies or alternatively rewriting URLs.

Java 'sessions' borrrowed some of their lexicon from the
naming conventions typically used with Hashtables. There
are 'put' methods and names referred to as  'keys'.
In order
to bring more consistency to the general API the 'put' methods
have been
deprecated and replaced with get and setAttribute
methods.

Methods that are used to manage session attributes
Methods used to manage a session object


You cannot place primitive data types into a session. Primitive
objects can be wrapped in their associated wrapper classes.
Java objects are entered into the session with the setAttribute(  )
method.

Example 

<%
PollBean poll  = new PollBean( );
session.setAttribute("poll",poll;
%>

Poll will now be available to all the servlets and JSPs belonging to
the same http session. The session object can be used to retrieve
object. Because the object has been stored as the parental Object
type, it will need to be cast back to it's more specific type.


Example 

<%
PollBean poll = (PollBean) session.getAttribute( "poll" );
%>

Recall a  JSP pages may choose to not participate in a session; by
setting it's page directive, session attribute to "false". 


Example
    <%@ page session="false" %>

Govind Seshadri suggests in his tutorial that large objects stored in sessions
may degrade performance as they are stored in heap memory space.

A typical default setting for a session object is 30 minutes. This value
can be reset with the setMaxInvalidationInterval( int sec) method. When
a session times out or is invalidated by the action  of the 'invalidate( )' 
method the session object is dereferenced which makes it available for
garbage collection.

The following servlet example is convenient to show the use of the
session object management methods.


Apache Servlet Example

 

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter( );

HttpSession session = request.getSession(true);

// print session info

Date created = new Date(session.getCreationTime( ));
Date accessed = new Date(session.getLastAccessedTime( ));
out.println("ID " + session.getId( ));
out.println("Created: " + created);
out.println("Last Accessed: " + accessed);

// set session info if needed

String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length( ) > 0 ) {
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
}

// print session contents

Enumeration e = session.getAttributeNames( );
while (e.hasMoreElements( )) {
String name = (String)e.nextElement( );
String value = session.getAttribute(name).toString( );
out.println(name + " = " + value);
}
}
}


Standard Actions


While actions tags supply page forwarding and services
for page includes, the real benefit of actions is associated
with the usebean tag. This tag allows Java code to be
separated almost completely from the presentation code.
This makes maintenance easier and promotes reusability.
We will deal with the forward and include actions first so
we are free to spend more time investigating the use of
JavaBeans in JSP pages.


Forwarding Requests

With the <jsp:forward> tag, you can redirect a request to
any JSP, servlet, or static HTML page within the same
web application. This results in a permanent transfer of
control. Processing of the forwarding page is halted and
continues with the receiving resourse. The action has the
following syntax. Notice the xml syntax where the jsp prefix
is used to namespace qualify the forward element. The
action takes the following form.

Form of the 'jsp:forward' Action

<jsp:forward page="LocalWebAppURL" />   

A <jsp:forward> tag may include 'jsp:param' subelements
that can be used to provide values for some elements in the
request used in the forwarding. The expanded form is as follows.

Expanded Form of the jsp:forward Action which Includes Parameters

<jsp:forward  page="LocalWebAppURL" >
   <jsp:param name="name1" value="value1" />
   <jsp:param name="name2" value="value2" />
</jsp:forward>

 
A Simple  JSP That Demonstrates the  'forward' Action

<!-- Note: Once the forward is done the page no longer changes on
        reload. This is because the forward represents a permanent pass
        of control,
not dynamic on each load.
-->


<html>
<head>
<title>
</title>
</head>
<body>
<% if (Math.random( ) < .5 ){  %>
   <jsp:forward page="Heads.html"/> 
<%   } else { %>
    <jsp:forward page="Tails.html"/> 
<% } %>  
</body>
</html>

// adding a random number generator to create different boolean values
// does nothing here except in deciding the first forward action. Once the
// action has occured the first page is not revisited. The transfer action
// is permanent

A Caution When Using <jsp:forward>

Any page that uses <jsp:forward> should be checked to see
if if the output buffer is large enough to ensure that it will not be
flushed before this tag is executed. This is because the forward
action clears the output buffer of  content that has been generated
to that point. If the action finds that the output buffer has already
been flushed before the forward takes place, the action will fail
and an 'IllegalStateException' will be thrown.

Including Requests

While the <jsp:forward> action is permanent, The <jsp:include>
tag temporily passes control to another resource then control
returns to the invoking page. The include tag stands in for the
location that the included material will be inserted. The 'include'
action takes the following form.

Form of the 'jsp:include' Action

<jsp:include page="localWebAppURL" flush="booleanFlag"/>

The page attribute identifies the resource that will be included,
whether a jsp, a servlet or a static html page. The value of the
'flush' attribute is by default "false". If  flush is set to "true",  error
page reporting,  or page forwarding will no longer be possible.
If set to 'false' these actions will still be permitted.

JSP pages that have been invoked through an include or forward
will have new pageContext objects assigned to them. They still will
participate in the scope of the request, session and application
objects. Transferred data is best stored in one of these objects.

Alternatively, the jsp:include action can also carry forward
parameters via param tags.

Form of the 'jsp:include' Action with Parameters

<jsp:include page "localwebappURL" flush="true">
<jsp:param name="param1">
<jsp:param value="value1" >
</jsp:include>

Whether to <%@ include %/> or to <jsp:include />

The <%@ include %> directive executes at translation and compilation
and as a result becomes a static part of the servlets output. This is
reflected in the fact that changes to included pages do not automatically
result in recompilation of the JSP that invokes the include directive.

The <jsp:include > action on the other hand is executing dynamically
at request servicing time. Dynamic changes to pages included through
the include action will be reflected in the pages output.

So the tradeoffs are these.

The include action offers automatic recompilation, smaller class
sizes, ( duplicate code in included files is not repeated in the page
servlet) and  actions supply the option to supply parameters. The
include action can also make use of request parameters.

Another limitation of the include directive it can only incorporate
template based documents, HTML and JSP and not servlets.
Pages using include directives have slightly better run time efficiency.
They don't need to pass requests to included pages. Also 'include'
directives are executed before servlet make use of the output buffer
so execute no cost on it.

The <jsp:useBean > action

The last action  is the useBean action. JavaBeans are easily a
topic of their own so we break this action out and introduce it in
the next note.




Self Test                                                      Self Test With Anwers


1) Can you recall what the name of the implicit object is that is associated
     with each of the following Java classes or interfaces?
     the following implicit objects.

a) HttpJspPage             __________         
b) ServletRequest         __________
c) ServletResponse       __________  
d) ServletConfig           __________
e) ServletContext         __________ 
f)  HttpSession             __________ 
g) ServletContext           __________ 
h) Throwable                 __________


2) True or False? The constants that represent JSP scopes
    contain integer
values. True \ False             
 

3) Which of the following is not a value of a scope in JSP?

a) application
b) sesssion
c) response
d) page                                                             
 

4) True or False? You can place a primitive data type as a value
of an attribute in a session object. True \ False     

 5) True or False? When ever the following tag appears in  a JSP page,
    a new bean instance is created. True \ False     

<jsp:useBean id="user" class="com.jguru.Person" scope="session" />
 

5) True or False? The include directive and include action work the same
     way and are just different syntax for the same thing.   True \ False