Chapter 10 JavaServer Pages (JSP)
JSP
- simplifies the delivery of dynamic Web content, using predefined
components and server-side scripting
- javax.servlet.jsp,
javax.servlet.jsp.tagext provide functionality
- Four key components to JSP
- directives - messages
to the JSP container that enable the programmer to specify page
settings, to include content from other resources, and to specify
custom tag libraries.
- actions- encapsulate
functionality in predefined tags that programmers can embed in JSP.
Often performed on the basis of info in a client request. Can
create Java objects for use in scriptlets.
- scriptlets- aka scripting elements enable
programmers to insert Java code that interacts with components in a JSP
to process requests.
- tag libraries are part
of the tag extension mechanism
that enables programmers to create custom tags. These tags enable
programmers to manipulate JSP content.
- JSPs normally include XHTML or XML markup. Such markup is
known as fixed-template data
or fixed-template text.
JSP is typically used when most of the content sent to the client is
fixed-template data and only a small portion is generated dynamically
with Java code. Servlets are typically used when only a small
portion of the content is fixed-template data. Some servlets just
perform a task for the client, then invoke other servlets or JSPs to
provide a response.
- In most cases, servlet and JSP technologies are
interchangeable. JSPs normally execute as part of a Web server.
The server is the JSP container.
- When JSP-enabled server receives the first request for a JSP, the
JSP container translates the JSP into a Java servlet. If there
are any errors compiling the new servlet, they result in translation-time errors.
- Java statements that implement the JSP's response are placed in
method _jspService at
translation time. If the servlet compiles properly, the JSP
container invokes method _jspService
to process the request. Any errors during request processing are request-time errors.
- Some JSP containers translate JSP at installation time, to
eliminate overhead for first client.
- JSP methods jspInit and jspDestroy are similar to servlet
methods init and destroy.
- Writing code to output markup (as in servlets) can often lead to
errors. Most JSP editors provide syntax coloring to help
programmers check their markup syntax.
- JSP expressions are delimited by <%= and %>
- The JSP container converts the result of every JSP expression
into a String that is output as part of the response.
- XHTML meta element can
set a refresh interval which
causes the brower to request clock.jsp
after each interval.
Figure 10.1: clock.jsp
Implicit Objects
- Implicit objects provide access to many servlet capabilities in
the context of a JSP. This is needed because JavaServer Pages are
not method calls, so the parameters etc. available in servlets need to
be provided in some fashion.
- They have four scopes:
- application - Owned
by the JSP and servlet container. Any servlet or JSP can
manipulate. The javax.servlet.ServletContext
object represents the container.
- page- exist only in
the page that defines them. The javax.servlet.ServletConfig
object represents the JSP configuation options. Can be specified
in a Web application descriptor.
- exception - the java.lang.Throwable object
represents the exception that is passed to the JSP error page.
Available only in a JSP error page.
- out - javax.servlet.jsp.JspWriter object
that writes text as part of the reponse to a request. Used
implicitly with JSP expressions and actions that insert string content
in a response.
- page - java.lang.Object represents the this reference for the current JSP
instance.
- pageContext - javax.servlet.jsp.PageContext object
that hides implementation details and provides JSP wth access to the
implicit objects.
- response - Normally
an instance of HttpServletResponse,
or an instance of a class that implements javax.servlet.ServletResponse, if
protocol other than HTTP is used.
- request - exist for
duration of request. A request can be partially processed by one
JSP, then forwarded to another servlet/JSP for further processing. They
go out of scope when response is made to client. Normally
an instance of class that implements HttpServletResponse
- session- exist for
client's entire browsing session. Available only in pages that
participate in a session.
Scripting
- In some cases, the content of generated XHTML documents is
static, but is output only if certain conditions are met (e.g.,
providing values in a form
that submits a request).
- JSP currently support scripting only with Java. Future JSP
versions may support other scripting languages.
Scripting Components
- Scriptlets are blocks of code delimited by <% and %>.
They contain Java statements that the container places in method _jspService at translation time.
- JSP comments are delimited by <%-- and --%>. Can be
placed throughout a JSP, but not inside scriptlets.
- XHTML comments are delimited with <!-- and -->. Can
be placed throught JSP, but not inside scriptlets.
- Scriptlets can use Java comments (delimited by // or /* and
*/).
- When clients view source code of JSP response, they will see only
XHTML comments. Comments that users don't need to see (about
logic processed on server) can be done with JSP or Java-type comments.
- Declarations are delimited by <%! and %>. They enable
a JSP programmer to define variables and methods. Variables and
methods are instance members of the servlet class that represents the
translated JSP. Declarations use Java syntax (e.g., must end in a
semicolon). <%! int counter = 0; %>
- Variables and methods in JSP declarations are initialized when
JSP is initialized and are available in all scriptlets and expressions
in the JSP.
- JSPs should not store client state information in instance
variables. Should use JSP implicit session object.
- Must use escape sequences
for characters used as JSP delimiters.
- <% -> <\%
- %> -> %\>
- ' -> \'
- " -> \"
- \ -> \\
- Scriptlets, expressions and fixed template data can be intermixed
in a JSP to create different reponses.
- JSPs can be difficult to debug, because line numbers reported in
JSP container refer to translated JSP servlet, not the original JSP
line numbers. Forte enables JSPs to be compiled in the
environment, so you can see syntax error messages
- The Tomcat installation directory contains a subdirectory called work where you can find source code
for the translated servlets.
Figure 10.4: welcome.jsp
Standard Actions
- Actions provide JSP implementors with access to common tasks
performed in a JSP.
- Actions are delimited by <jsp:action>
and </jsp:action> where actionis the standard action name.
- Can use </action
/> if nothing appears between start/end tags.
- <jsp:include> -
dynamically includes another resource in a JSP.
- <jsp:forward> -
forwards to JSP, servlet or static page. Terminates current JSP's
execution.
- <jsp:plugin> -
Allows plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. Can be an
applet, which enables downloading the Java Plug-in, if not already
installed.
- <jsp:param> - Used
with include, forward and plugin actions to specify additional
name/value pairs of information.
- <jsp:useBean> -
specifies that JSP use a JavaBean instance. Specifies the scope
of the bean and assigns it an ID that scripting components can use to
manipulate the bean.
- <jsp:setProperty> -
sets a property in the specified JavaBean. Matches request
parameters to bean properties of the same name.
- <jsp:getProperty> -
gets a property in the specified JavaBean, converts the result to a
string for output in the response.
JSP supports two include mechanisms:
- The include directive
copies the content into the JSP once, at translation time.
- <jsp:include> enables dynamic content to be included.
If the included resource changes between requests, the next request
includes the new content. This is more flexible than the include directive, but requires more
overhead. Use only when necessary. Includes attributes:
- page- specifies the
relative URL of the resource to include. Must be part of the same
Web application, or a request-time
error occurs.
- flush- specifies
whether buffer should be flushed after include
is performed. In JSP 1.1, required to be true. If this attribute is not
specified, a translation-time
error occurs.
Figure 10.7: include.jsp
Figure 10.11: forward1.jsp
Plugins
- type - Component type:
bean or applet
- code - class that
represents the component
- codebase - location of
class specified in the code
attribute and archives specified with
archive attribute
- align - alignment of the
component
- archive -
space-separated list of archive files that contain resources used by
the component. May include the class specified by the code attribute.
- height - component height
specifed in pixels or percentage
- hspace- number of pixels
of space that appear to the left and to the right of the component.
- jreversion - version of
Java Runtime Environment and plug-in required to execute
component. Default is 1.1.
- name - name of component.
- vspace- number of pixels
of space that appear above and below the component.
- title - text that
describes the component.
- width - component
width specified in pixels or percentage.
- nspluginur1- location for
download of Java Plug-in for Netscape
- iepluginurl - location
for download of Java Plug-in for Internet Explorer
- Most Web browsers do not support applets written for Java 2
platform, so you must use Java Plug-in.
useBean Action
- has attributes that can be manipulated:
- id - name used to
manipulate the Java object with actions <jsp:setProperty> and <jsp:getProperty> A variable
of this name is available for use in scripting elements. The bean
should name properties using set
and get in order to work with setProperty and getProperty.
- scope- Can have page, request, session or application scope that indicates
where they can be used in a Web application.
- class - fully qualified
class name of the Java object
- beansName - name of a
bean that can be used with method instantiate
of class java.beans.Beans to
load a JavaBean
- type- Can be the same
as the class attribute, a
superclass of that type or an interface implemented by that type.
A ClassCastException occurs if
the Java object is not of the type specfied with the attribute type.
- One or both of type and class must be specified, or a
translation-time error occurs
Rotator example
setProperty
- can be used to set JavaBean properties
- Often used to map request parameter values to JavaBean properties
- Can set primitive types boolean, byte, char, int, long, float,
double and java.lang types
String, Boolean, Byte, Character, Integer, Long, Float and Double.
- Attributes used with setProperty:
- name- ID of JavaBean
- property - name of
property to set. Can specify '*' to cause JSP to match the
request parameters to the properties of the bean. If the value of
the request parameter is "", property remains unchanged.
- param- Can be used to
specify which request parameter to use, in case names do not match bean
properties. If omitted, names must match.
- value - value to
assign. Often the result of a JSP expression. Used when
property types cannot be set with request parameters (avoid conversion
errors).
Handling Exceptions
- When a JSP performs an operation that causes an exception, the
JSP can include scriptlets that catch the exception and process
it.
- Exceptions that are not caught can be forwarded to a JSP error
page.
- page directive defines
information that is globally available in a JSP
- Directives are delimited by <%@ and %>
- errorPage attribute
specifies page to handle all uncaught exceptions
- isErrorPage set to true creates a page that can be used
to catch errors
- the implicit object exception
can only be used in error pages
GuestBook example
Directives
- Messages to JSP that enable you to specify page settings, to
include content frmo other resources, and to specify custom-tag
librairies. Directives are processed at translation time (i.e.,
before any requests are received).
- There are three directive types: page, include and taglib.
- page directive specifies
global settings for the JSP. There can be many page directives,
as long as there is only one of each attribute (except import). Attributes include:
- language - scripting
language used, currently must be java
- extends - class from
which JSP will be inherited, must be fully qualified
- import -
comma-separated list of fully qualified names/packages to be used.
- session - specifies
whether the page participates in a session. Default is true,
which makes the implicit object session
available.
- buffer - size of output
buffer used with implicit object out.
Can be none or a value such as
8kb (the default).
- autoFlush - If true
(the default), indicates buffer associated with out should be flushed automatically
when full. If false, an exception occurs when the buffer is
full.
- isThreadSafe - If true
(default), the page can process multiple requests at the same
time. JSP allows multiple instances of a JSP if not thread safe.
- info- information
string that describes the page. Returned by getServletInfo method.
- errorPage - processes
exceptions.
- isErrorPage - if true,
will handle exceptions.
- contentType - MIME type
of data in response, default is text/html.
- include includes the
content of another resource one, at compile time. Only attribute
is a file that specifies the URL of the page to include.
<jsp:include> is processed each request to the server, so should
be used if content of included resource can change.
- taglib directive allows
creation of custom tags. See text for details.