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,
Web Development with
Java
Server Pages, Duane Fields, Mark Kolb and Shawn Bayern
Overview
Java Server Pages are a basic currency of the
Enterprise Application and is the recommended
vehicle for making presentation of information to
the user. So it makes sense to look at them in
some detail.
Another point, many of the aspects shown for JSP
pages have equivalent counter parts in the Java
Servlet code. We alert you to this, but focus on
the JSP counterparts of the Java Servlet code.
This puts those who are strong Java programmers
more on the same footing with those not as familiar
with Java.
Java Server Pages have a syntax that is similar to
Microsoft ASPs. Beyond these character groupings
JSP
relies on XML to supply the rest of it's syntax
needs.
JSP syntax can be classified into directives, scripting
elements,
and standard actions. Added In version 1.2
is a syntax to serve in XML documents.
The XML syntax has similarities and differences from
the HTML
syntax. To introduce JSP syntax, we will
concentrate on the HTML version
of the dialect.
// a brief discussion of the parallel
XML version is
// carried in subtext which we can
ignore for expedience.
Directives
Directives control JSP page
execution parameters,
in other words, the
global properties of the JSP page.
Directives of themselves
do not produce direct visible
output and are only there to tell the JSP engine to do
something.
JSP directives are always enclosed within the
<%@ ... %> tag.
where the percent symbol is
followed by the @ symbol.
Containing Braces of JSP Directives
<%@ . . . %>
There are three directives defined in the the JSP
version 1.2
specification, the 'page', 'include' and
'taglib' directives. Though,
'include' and 'page' are
commonest while the 'taglib' directive is becoming
more popular with the adoption of custom tags.
JSP Directives
The 'page' Directive
The page directive is found at the top of almost all
JSP
pages. There can be any number of page
directives in a JSP page as long as their
attribute
value pairs are unique. If unrecognized attributes or
values are used
with the page directive a translation
error results. Following is a simple form
of the page
directive.
Simple Form of a Page Directive
<%@ page attribute1="value1"
attribute2="value2"
atributeN="valueN" %>
That the 'page' directive can be very complicated as
indicated by the comprehensive form of this directive
below. This form is
shown next and shows all the options
made available to the JSP page authors
through it's
various attributes.
The Page directive with Attributes That Apply to a JSP Page.
<%@ page
[ language=" java " ] [ extends=" package. class "]
[ import="{ package. class | package .*} , ... " ]
[ session=" true |false" ]
[ buffer=" none| 8kb | size kb" ] [ autoFlush=" true
|false" ]
[ isThreadSafe=" true |false" ] [ info=" text "]
[ errorPage=" relativeURL " ] [ isErrorPage=" true|
false "]
[ contentType="{ mimeType [ ; charset =characterSet ]|
text/ html ; charset= ISO- 8859- 1 }" ]
[ pageEncoding="{ characterSet | ISO- 8859- 1 }" ]
%>
// XML reference: the XML
page directive:
// <jsp: directive. page pageDirectiveAttrList
/>
// where pageDirectiveAttrList
is the same as the
// list above in the JSP page directive
The above form can be broken out in table form for
ease of reading. The following table summarizes
the
12 attributes of the 'page'
attribute.
The attributes are used to control things like the
language being used, what packages are imported
and may allow the JSP to extend a class. They are
summarized below for your reference.
Table Summarizing the 12
Attributes of the 'page' Attribute
Attribute Name | Constraints | Default Value |
Description |
language | language="java" | "java" | scripting language to be used |
extends | extends="pkg.class" | none | optionally allows the JSP to extend the class specified |
import | import= "{package.class | package .* } , ... " |
none | makes
packages avaiilable to the compiler |
session | session=" true | false" | "true" | decides whether a session is associated with this request /response |
buffer | buffer="
none | 8kb | size kb" |
"8kb" | decides if a page is buffered & what size the buffer will be |
autoflush | autoFlush=" true |false" | "true" | makes sure buffer is flushed before sending response |
isThreadSafe | isThreadSafe=" true |false" | "true" | can
assume
responsibility for assuring thread safety |
info | info=" text " | none | supplies
page
descriptions to associated applications |
errorPage | errorPage=" relativeURL " | none | specifies
a page to
forward to in case of an exception |
isErrorPage | isErrorPage=" true| false " | "false" | identifies a page as being an error page |
contentType | contentType="{mimeType [;charset =characterSet] | text/html; charset=ISO-8859- 1 }" |
"text/html"
/ ISO-8859-1 |
specifies the MIME content type for page& optionally a character set. |
pageEncoding | pageEncoding= "{characterSet | ISO- 8859- 1 }" |
"ISO-8859-1" | specifies
a
character set for the page |
Following is a brief description of these attributes.
The 'language' Attribute
While Java is the default, this tag offers the
possibility of
using other languages like JavaScript if the hosting server
supports other languages. If no language attribute is present,
the scripting language is assumed to be Java.
The 'extends' Attribute
The 'extends' attribute can be
used by a JSP author to
tell the container to use a different implementation
of the
HttpJspPage interface. The 'extends' attribute followed by
the
specified name will be appended to the class name in
the Java source code. It is
expected that this attribute would
be used only rarely for very specialized
JSP applications.
Example
<%@ page extends="XT.HttpJspPageXtra" %>
Java Snippet
MyJSP extends MyHttpJspPage{ // ....
The 'import' Attribute
// the
only 'page'
attribute that may appear more than once
The 'import' attribute and corresponding value translates
into import statements in the corresponding Java source
code. The import attribute
is the only attribute that can
appear more than once inside a JSP page.
The attribute
can be used in the singular or in a plural sense.
For
instance, the following example showss an import of
all classes in the io package.
Example <%@
page import="java.io.*" %>
Java Snippet
import java.io.*;
class IOer{ // ...
Additional import statements can be added to the
page or multiple
packages can be specified as a
comma separated list.
Example
<%@ page
import="java.awt.Window, java.io.*, java.util.Vector" %>
// Where
to put the imports: A quick survey shows some authors
// putting the
imports ahead of the introductory html tag. Others
// leave out the head of
their html page and put the tag between
// the html tag and the body. Another page
showed the import as
// the first tag in the body.
Also some pages have imports between
// head and body tags. It works to put the imports in the head
tag.
// Because the
page will be translated issues of forward referencing
// do not appear to be relevant.
// Between
the head and body tags or as the first tag inside the body
// seems like good locations to put page directives.
The 'session'
Attribute
The session attribute tells whether the page will
participate in a
HTTP style 'session' represented in
the JSP world as a HttpSession object. The
default
value for this attribute is 'true'. Specifying this attribute
will usually be
used to turn session participation off.
Turning session participation off will yield
a small
performance gain.
// Servlets has Session class that is
manipulated directly from
// the Java code
The 'buffer' Attribute
In order to provide an exit strategy in
case an error
arises and to provide some 'breathing room' where
a JSP can 'decide' to forward a request to another
page, the JSP environment supplies buffers. A buffer
is a
memory area where page code can be sent and
assembled before it is sent off to
a client.
Large vs Small Buffers
The buffer attribute is used to control
the characteristics
of
the buffer. A larger buffer allows more content to be
written before anything is
sent back to the client. This
gives the JSP page more time to set up status
codes
and headers as well as forward requests to other Web
locations. A
smaller buffer allows a client to start to
receive output data more quickly.
The default value for the size of the
memory buffer is 8
kilobytes, specified as "8kb". If the 8 kilobytes is full, the
default container behaviour
is to send what is in the buffer
to the client. If the value is set to
'none', the page will be
streamed as is, unbuffered. This eliminates the possiblity
of
forwarding or hiding errors that may be generated.
The buffer size can be
increased as required, although
the default value should handle the great majority
of JSP
pages.
Form of the Buffer Attribute
<%
page buffer="none| 8kb | size kb" %>
In the following example the Java sql package is being
imported and the
buffer is being set to 16 kilobyte.
Page Directive Example from Magelang Tutorial
<%@ page import="java.sql.*, com.foo.*" buffer="16" %>
// buffer value may have been
specified
as "16kb".
The
'autoFlush' Attribute
There is also an 'autoFlush' attribute has a default value
set to true. This results in the default behaviour
where the
buffer is flushed when filled, the page being streamed
'as is' to the
client.
If the autoFlush attribute is set to false, then the container
will
instead throw an exception. providing
an opportunity
for handling
the exception and sending
something other
than an incomplete response.
The 'isThreadSafe' Attribute and Synchronization in JSPs
This attribute relates to Java's
intrinsically multithreaded
environment. Java allows many threads to run at the same
time. If these threads are allowed to simultaneously access
sensitive
data, there is a potential for the data to be corrupted.
Java synchronizes data so that it is threadsafe.
The JSP
'isThreadSafe' attribute by default is set to true
providing inherent thread safeness for the page. . This
presumes the page is 'thread safe' and there is no chance
of
simultaneous threads hitting on shared data simultaneously
resulting in corrupted or
incorrect data reading.
Example
<%@ page isThreadSafe="false" %>
This will cause the container to play
it safe and 'inline'
responses to client requests, effectively synchronizing the
response code. The problem with
this conservative
approach is that queuing requests may greatly reduce
throughput efficiency. This may be OK in the case of a
little used but important service.
The Better Approach
The better approach, is to leave the
'isThreadSafe' attribute
at it's default setting and be careful to synchronize accesses
on shared data by
marking methods that access shared data
'synchronized'.
All static
variables and objects that are in session or application
scope should be inspected
to see that they are thread safe.
Following, is an example from Govind
Seshadri's JSP tutorial
where a synchronized block is used to ensure a
shared object
is only accessed safely by one thread at a time.
Example from Tutorial by Govind Seshadri
<%
synchronized (application) {
SharedObject foo = (SharedObject)
application.getAttribute("sharedObject");
foo.update(someValue);
application.setAttribute("sharedObject",foo);
}
%>
// the synchronized keyword is commonly
applied to methods
The 'info' Attribute
The 'info' attribute is used to
associate a description
with the page being generated.
This value can be
retrieved by
applications to communicate what
a JSP
page can do. This is a good location
for including
author and publishing
information.
The errorPage Attribute & Exception Handling
JSP pages supply an interesting technique for
handling exceptions.
While, you can provide
your own exception handling within JSP pages
using 'try,
catch and finally' blocks there may be
circumstances where one might 'get
away'.
Java Server Pages allow the use of the 'errorPage'
attribute to forward an
uncaught exception to an
error handling page.The error handling page then
takes
care of processing the error. The form of the
errorPage attribute is straight
forward as is shown
below.
Form of the errrorPage Attribute
<%@ page errorPage="file_name" %>
There also is an 'isErrorPage' attribute that can be
set to true or
false. It is used at the beginning of an
error page to indicate it is serving this
role.
The following example states that the current page
is not an error
page and that in case of an error it
wishes the request to be forwarded to
the the
exceptionHandler.jsp page.
Example
<%@ page isErrorPage="false" errorPage="exceptionHandler.jsp" %>
Note, it is also necessary for errorHandler.jsp to flag itself
as a
error processing page using the following directive.
Example
<%@ page isErrorPage="true" %>
This directive allows the Throwable object to be accessed
within a scriptlet through the implicit exception object.
// implicit objects are covered in the next note
Following is a complete example that shows how the
errorPage
attribute is used.
A JSP That
Specifies An Error Page
//
Saved as DivideError.jsp under Web Content
// of Project
The Corresponding
Error Page
// saved as errorPage in same location as above
The
pageEncoding and contentType Attributes
JSPs can be used to create a page in
any kind of
text format, i.e. HTML, WML or XML as long as the
content conforms with that model. To use a format
other then HTML you include the contentType attribute
in the page directive. The following example from the
Magelang Institute tutorial shows 'Wireless Markup
Language' or WML being specified as the content
type.
J2EE Tutorial Example
<%@
page
contentType="text/vnd.wap.wml" %>
The registry of content types is kept by IANA at this link.
ftp://ftp.isi.edu/in-notes/iana/assignments/media-types
The 'contentType' attribute allows the setting of the MIME
type for
the page. This value will be typically set to "text/html"
or "text/xml".
The 'pageEncoding' attribute can also be set
inside this attribute. The
default value for pageEncoding is
"ISO-8859-1". The form of the attribute is repeated below
followed by an example.
Form of contentType attribute
contentType="{ mimeType [ ; charset =characterSet
] |
text/ html ; charset= ISO- 8859- 1 }"
The following example shows the combined form.
Example of both values being set at the
contentType attribute
contentType= "text/html;charset=ISO-8859-1"
Page encoding can also be set using the
'pageEncoding'
attribute. The following example shows this
approach which
appears
clearer to read.
Content type and page encoding set, each using their own attributes
<%@ page contentType="text/xml" pageEncoding="ISO-8859-1" %>
The 'include' Directive
The 'include' directive lets you distribute page content into
manageable elements. An 'include' might be used to include
a page header or
footer. Included pages may be static HTML
or more JSP content. The 'include' directive can be located
anywhere in the JSP page. The directive acts as a placeholder
where the file it points to will be located inside the
containing
document.
Net effect of the 'include' Directive
Including Page + Included Pages --> Combined Source --> Combined Page Servlet
Duane Fields et. al. in 'Web Development with Java
Server
Pages' note that it is recommended that only
top level pages use the .jsp
extension, and other jsp's
that are included use a sub-referencing extension type
such
as .jspf or .jsf., where the 'f' stands for jsp fragment.
They also point
out that the JSP container automatically
rebuilds and recompiles whenever the
file containing the
pages contents is modified. This does not apply to
modification to included files. To introduce included
changes an explicit update to
the time of modification
of the top level file needs to take place.
//
Open and resave the file
Following is the formal form of the
directive.
Include Directive Form
<%@ include file="relativeURL" % >
Next, an example of an include directive is shown.
Include Directive Example
<%@ include file="logos/CompanyHeader.html" %>
// The XML include
directive for reference :
// <jsp:directive.include
file="relativeURLspec"/>
A Java Server Page that needs additional work is
exampled next. You are asked at the end of the note
o finish this example as a 'hands-on' exercise. One
of the 'include' directive is highlighted in a
shade of
green.
Java Server Page that Includes HTML files
<html>
<head>
<title>
JSP 2
</title>
<body>
<H1>A Seasonal Demonstration of the 'include'
Directive</H1><HR/>
<%@ include file="Spring.html" %>
<%--
<%@ include file="Summer.html">
<%@ include file="Fall.html">
<%@ include file="Winter.html">
--%>
</body>
Included HTML
<html>
<head>
<title>
Spring HTML
</title>
</head>
<body>
<H2> It's Spring! Spring has Sprung!
</H2>
</body>
</html>
The taglib Directive // just for reference
The 'taglib' directive defines a tag library and a prefix
for custom
tags that are used in a JSP page. The 'taglib'
directive has the following form.
We defer looking at tag
libraries for now.
Form of Taglib Directive
<%@ taglib uri="URI" prefix="tagPrefix" %>
Following is an example from a tutorial called "Developing
JSP
Custom Tags" by Qusay H. Mahmoud. The taglib
directive informs the JSP container that custom tags are
used in the page and their definitions can be found at the
specified location. The file located is
specifically the
'Tag Library Descriptor' File for the library.
The TagLib directive
also supplies the prefix that will act
as a namespace qualifier for the
custom tags. There are
no restrictions on how many tag libraries are
referenced
in a page. Name clashes are avoided by use of the
namespace prefix. The JSP specification requires that
the Java classes that supply the
tags actions be stored
locally for security reasons.
JSP Custom Tags Tutorial Example
<%@ taglib uri="/WEB-INF/jsp/TagLibrary.tld" prefix="tagLibPrefix" %>
// for reference: no XML
equivalent. This action is handled as attributes of the root
element
Each custom tag will take the following form.
Detailed Form of the Custom Tag
< tagPrefix : name attribute =" value "+ ...
/>
| // simple form or . . .
< tagPrefix : name attribute =" value "+ ... >
other tags and data
</ tagPrefix : name >
// for
reference: The XML tag is the same as the detailed tag shown here
Declarations
JSP declarations let you define variables and methods
for use within
a JSP page. If not initialized, variables are
set to default values for
their Java types.
Consider a financial page might have special constants
and values such as the days prime rate and methods that
use this data, for instance in mortgage or interest rate
calculations. These would all be candidates for declaration
in JSP declaration tags.
While it is tempting to use declarations to supply such
information,
it is often better to hide this complexity in
JavaBeans which we can access from a page.
Still there is a place for everything so we consider in
the following, the form of the declaration. While the key
character that distinguished directives was the 'at'
symbol, @ , the exclamation mark, !, is the unique
symbol used in declarations. The following shows that
there may be one or more declarations in a single
declaration tag.
Declaration Form
<%! declaration; [declaration; ]+ .
. . %>
// JSP refers to + as
'can repeat' and '. . .' as 'list of items'
The form used in 'Web
Development With Java Server
Pages' is perhaps more straight forward to understand
if not formal.
Alternate Form
<%! declaration(s) %>
Declarations contain Java statements. A variable statement
will
always end with a semi-colon. The following example
shows this.
Example of a Declaration of a variable.
<%! double j=7.67;
%>
//
declaration statements end in semi-colons or a closing curly braces
For those who can use a bit of Java review, the following
compound
declaration shows all the java primitive types
along with a class String example
being used.
Example of a Declaration of a variable.
<%!
boolean boo
= true;
char
zee = 'Z';
short
twoBytes =32000;
int
fourBytes = 2000000000;
long
reallyBig = -9000000000000000000L;
float
low_temp=2.4F;
double
high_temp=22.8;
String story="Can you tell the story associated with
these variables?";
%>
At times it may be quicker to test script
components for
correctness in straight Java before migrating the code
to a JSP
Using Java to Test Before Migrating to the JSP
class Var{
public static void main(String[]args){
boolean boo = true;
char
zee = 'Z';
short
twoBytes =32000;
int
fourBytes = 2000000000;
long
reallyBig = -9000000000000000000L;
float
low_temp=2.4F;
double
high_temp=22.8;
String story="Can you tell the story associated with
these variables?";
System.out.println(story);
System.out.println("Yes, it is " + boo + " " + zee +
"ephaniah!");
}
}
Class vs Instance Variables
The authors of 'Web Development with Java Server Pages'
state that in the stock case where the 'isThreadSafe' page
attribute is
set to true, is a guarantee from the container that
only one instance of the class is being used to service request
threads at a
time and data integrity is being maintained.
In this condition, whether variables are instance variables,
(associated with the servlet instance object) or are class
variables marked
'static', the net effect may essentially be
the same. This is because in both situations there is
effectively a 'one of' condition being maintained.
On the other hand, if 'isThreadSafe' is set to false and the
container is free to issue any number of instances of the
servlet then marking
variables 'static' becomes significant
and neccessary where variables need to be shared across
requests.
The following counter variable would need to be marked
'static' in
order to be shared by multiple servlet instances.
A set of instances of the
same page servlet would all
increment the same shared, counter variable.
Example
<%! public static int counter=0 %>
Method
Declarations
Methods are also declared
inside declarations tags. The
following method concatenates a period to the first letter
of a name to form an initial.
<%!
static String getInitial(String name){
char initial= name.charAt(0);
return (initial + ".");
}
%>
Overriding Life Cycle Methods // for reference only
Whenever a JSP servlet object is run it's life cycle
methods are
called. Life cycle methods are a set
of methods that run in sequence and are called
over an objects life time from it's inception to the
object's cessation.
While the JSP developer cannot override all of these,
jspInit( )
and jspDestroy( ) are available for overriding.
Recall overriding
involves imitating a method signature
exactly. In the body of the overridden method though,
custom changes can be introduced to meet the needs
of the developer.
The jspInit( ) method is called once after the servlet is
instantiated but before any requests are answered. A
typical sort of thing to do in
jspInit( ) might be to initialize
a database connnection.
The jspDestroy( ) method will be called after all requests
have been
answered but before the servlet object is
removed from service. The jspDestroy( ) method can be
overridden close out any streams that may have been
opened and perhaps to set stream references explicitly
to
null.
Example of a Declaration of a Method being Overidden
<%! public void jspInit( ){
// i.e. initialize
database connection
}
%>
<%! public void jspDestroy( ){
// i.e. close out
streams and resources
}
%>
Expressions
JSP expressions explicitly resolve to string values
that are
directly included in the output of JSP pages.
Simple variables, expressions or methods
that resolve
to some values can all be inserted into the output of
a JSP
page via an expression tag.
The hallmark of the JSP expression tag is the 'equals'
symbol, " = ".
Another notable feature that is unlike
declaration counterparts, expressions do not
include
closing semi-colons. Following is the formal form of
a JSP expression.
Form of a JSP Expression
<%= . .
. %>
// expression tags do not
include
semicolons
The variables we declared earlier would be candidates
for inclusion
in expressions.
A boolean type Declaration
<%! boolean boo = true; %>
Example //
inside an HTML body tag
That day follows night is <%= boo %>
// evaluates into the HTML a string
representation of true.
We have yet to work with Java objects
but they
can
be used to call methods on whose return values
will
resolve directly to a
string in a JSP page.
Magelang Tutorial
Example
<%= fooBean.getName( ) %>
One more example, the String object we named 'story'
declared
above can be used to call a method that
returns the value as upper case text.
String Method in an
Expression Example
<%= story.toUpperCase( ) %>
// resolves directly into the page as
// 'CAN YOU TELL THE STORY ASSOCIATED WITH THESE VARIABLES?
Expressions convert all
primitive types or Java object
types to character strings. ( With objects the
toString( )
method is called.)
// Wrapper or object toString( ) methods convert all types to JSP output
The authors of 'Web Development with Java
Server Pages'
point out that Java's one ternary
operator, the abbreviated,
if . . . else operator is very useful in JSPs for it's ability
to make
a choice in such a small amount of code. The ternary operator
has
the following form.
Java's if else Ternary Operator
a = (boolean expression) ? b : c;
The following complete JSP example
shows the ternary operator
in action.
<html>
<head>
<title>
New
</title> gedit
</head>
<body>
Hello Bob!
In terms of AM and PM it is
<%! int hours = 18; %>
<%= (hours < 12 ) ? "AM" : "PM" %>
<!-- scriptlet evaluates to 'PM' -->
</body>
</html>
Scriptlets
All the tags we have described so far have an extra symbol
associated with them, (@, ! , = ). JSP 'scriptlets' are embedded
inside the plainer and generic, <% ... %> tag.
The scriplet tag is JSP's general
purpose scripting construct.
Scriptlets are like declarations in that they do
not evaluate to a
result that is entered in the page in the way the jsp
expression
tag works. Below is the form of the scriptlet tag.
Form used by a JSP Scriptlet
<% . . . %>
Scriptlets are run when a request is serviced by a JSP page.
Scriplets are used to contain sections of valid Java code and
are not limited to a
single line of code. The following code is
part of a Magelang Institute
example that shows how scriplets
can be used to hold multiple lines of Java
code.
// don't worry about the code for the moment. We are just
showing that a scriptlet
//
can contain an arbitrary number of lines, objects can be declared
and
// instantiated, methods can be called
and control statements can be executed.
Excerpt from a Magelang Institute Code Sample
<%
String selectedLocale =
request.getParameter("locale");
Iterator i =
locales.getLocaleNames().iterator( );
while (i.hasNext( )) {
String locale =
(String)i.next( );
if (selectedLocale !=
null &&
selectedLocale.equals(locale)) {
%>
<!-- puts locale out to the document -->
<option selected><%=locale%></option>
// notice the Sciplet's declaration was recognized by the
// expression
In the following Magelang Institute example, there is a
short
scriptlet that starts the 'triplet', a middle section of
template data with jsp
expressions included and a second
closing scriptlet. The output is the text,
'Hello' in different
header sizes.
Magelang Institute Example
<% for (int i=1; i<=4;
i++) { %> <!--
starting scriplet 1 -->
<H<%=i%>>Hello</H<%=i%>> <!--
template code with expressions added -->
<% } %> <!--
ending scriplet 2 -->
// while fun this might be asking for
maintenance trouble
This shows an interesting aspect of JSP script that can be
confusing
to read and track. I have added some colors to
try and make it easier
to see the component parts. The Java
and the template code are
interleaved. Java code scriptlets
exercise control over output that is in turn
expressed in the
parallel domain of the template data.
The key to following such code
is to remember control actions
take place in the Java while output is
always in the template
domain, by default HTML.
The scriptlet can be used hand in hand with an expression.
The
following complete JSP example shows a code block
rendered in a scriptlet and values that are created referenced
into the page using expressions.
Complete JSP sample showing
Scriptlets and Expressions working in Concert
<html>
<head>
<meta content="text/html;charset=ISO-8859-1"
http-equiv="Content-Type">
<title>
Scriptlets
</title>
<body>
<%@ page import="java.util.*" %>
<%
Vector v = new Vector( );
String name1 = "Betty Crocker";
Integer number1 = new Integer(1001);
// have to add
number as object type so use wrapper class
// notice we
get to use Java's own comment style inside
String name2 = "Davey Crocker";
Integer number2 = new Integer(2002);
v.addElement(name1.toUpperCase());
v.addElement(number1);
v.addElement(name2.toUpperCase());
v.addElement(number2);
%>
<!--
We didn't really need the Vector but it is included
to show Scriplets can do any kind of Java.
-->
<title>EX1</title>
</head>
<body>
<small>DEAR <%= v.elementAt(0)%><br>
IT HAS COME TO OUR ATTENTION THAT YOU <br>
ARE NOT PLEASED WITH THE NUMBER, <%= v.elementAt(1)%>. <br>
<br>
<br>
PLEASE TALK TO OUR NUMBERS
DEPARTMENT<br>
TO OBTAIN A NEW
NUMBER.
<br>
<br>
THANKYOU
<br>
CUSTOMER RELATIONS<br>
<br>
</body><br>
<html></small>
</body>
</html>
Comment Types in JSP Pages
JSPs can use three sorts of comments. Standard
HTML comments can be used which are invisible in
the browser view but visible in the
HTML. Following
is the HTML form.
Form of an HTML Comment Tag
<!-- HTML style comment -->
Inside JSP tags standard Java comment styles can
be used. There are
three Java tag types. The single
line form inherited from C++ and the classic
C form
for multiple lines. These two forms are shown below.
Form of a Java Single Line Comment
// Single line comment inside Java code inside tag
// careful! this comments out this
end of tag delimiter, %>
Form of Java Multiple Line Comment Style
/* This Java comment is a the form borrowed
from C that can extends across several
lines. */
Scripting language comments are forwarded as part
of the HTML presentation.
// Javadoc comments should also would work in
JSPs
/**
Special form used to generate
Java docs */
The JSP Comment Type
Last but not least is JSPs own comment style. It uses a mix
of familiar % sign and the two hyphens. This form is important
as these comments are not forwarded as part of the code sent
to the client. These can be used to add documentation that is
confidential to the server side JSP documents. We will show
an example of this tag in the next section.
<%-- . .
. --%>
Error
Handling Inside Java Server Pages
We
saw earlier in the note that JSP supplies the mechanism
where an error condition can result in forwarding a request
to an error page for handling.
Java's
built in errror handling facilites can also be used to handle
errors without leaving the page. If you are not already familiar,
Java uses 'try, catch and finally' blocks to catch errors, report
on them and then continue on with processing. The following
is a complete JSP sample that shows a 'try catch' pair being
used in the context of a JSP page. I have highlighted the JSP
and the JSP comment is italized and presented in green.
Error
Handling using 'try catch' Blocks Inside a JSP Page
<html>
<head>
<title>
Problem Houston!
</title>
<body>
<H2> Houston Space Center
</H2><HR><HR/>
We are in a page working with
numbers
and
<BR><BR/>
an unexpected problem is about to
arise.
<BR><BR/>
We could send the error to an error
page but
<BR><BR/>
because this is Java we can handle
such a
<BR><BR/>
problem using try, catch, finally
blocks.
<%
try { int i = 1/0; }
/* we can
catch this problem internally */
catch(Exception
ae){
%>
<BR></BR><BR></BR>
<HR></HR><HR></HR>
WE HAVE A PROBLEM
HOUSTON!
<BR><BR/>
WE HAVE THROWN A <B> <%=
ae.toString() %>
</B><BR></BR>
THE getMessage( ) METHOD REPORTS THE FOLLOWING:
<BR></BR>
<B> <%= ae.getMessage() %>
</B>
<%-- The
toString() reports the exception name and
the message that is returned by getMessage()
This is also our JSP style comment and will not
be visible to the
client
--%>
<% } %>
</body>
</html>
2)
Fill in the name of the
page attribute and the default value for each
of the following desciptions.
i)
_________ used to provide page
information
( default value ) _____________
ii) _________ decides if the page
participates in a session
( default value ) ______________
iii) _________ used to make java
packages available to page's java code
( default value )_______________
iv) ________ attribute that
dictates scripting language chosen
( default value)_______________
v) ________ used to
change the default superclass of a jsp servlet
(default value) _______________
vi) ________ used to control
buffering characteristics of page response
( default value )______________
vii) _______ decides if buffer
sends when full or will throw exception
(default value ) ______________
viii) _______ tells the container
the page is safe to multithread
( default value ) _______________
ix) ________ tells the container
that this page is an error page
(default value ) _______________
x ) ________ tells the container
what the MIME type of the page is
( default value ) _______________
3) A declaration tag uses which of the following symbols
a) @
b) !
c) =
d)
*
4 ) True or False: A
declaration contains statements that end
with a semi-colon or a curley
brace
5 ) Expression use which of the following symbols.
a) @
b) !
c) =
d)
*
6) True or False:
An expression contains a statement that ends in
a semi-colon.
7) What is the form of a JSP
comment? _________
// There
is not time to do all these. More than less is
// included just in case
some
of you are speed demons.
In all the following examples, add JSP comments that briefly
describe the page.
1) Complete the include example for the 4 seasons. Copy
into a New JSP Template in Eclipse. Without getting carried
away, feel free to add a little bit of color and formatting to your
example.
2) Create a JSP page and a matching error page that will be
invoked in the case of some unknown exception being created.
Use the bit of code that throws an divide by zero exception and
test in Apache just to confirm you error page is set up correctly.
3) Use variations of the primitive type declarations and method
example to declare some values and methods for a JSP page.
Use expressions to intercolate their values with template text.
optional
4) Declare an array of names that can be referenced inside a JSP
page. Use expressions to enter the array values into the beginning
of a form letter that is created using static template text.
block that catches an ArrayOutOfBounds
exception. Cause
the code to loop out of bounds to demonstrate
the error
handling.