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
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.
There are four implicit objects that can store
attributes
each which have static constants associated with them.
Object
that can Store Attributes:
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.
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);
%>
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.
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:
|
Defined in
HttpServletResponse are methods to set
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 |
HTTPServletResponse also defines the methods used
<%
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);
}
}
}
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.
<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.
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
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"
/>