Title: Internet programming JavaServer Pages
1Internet programmingJavaServer Pages
- Prof. Dr.-Ing. Holger Vogelsang
holger.vogelsang_at_hs-karlsruhe.de - Dipl.-Ing. Uwe Endress
- privat.uwe.endress_at_isb-ag.de
- 0721 / 756460
- http//www.home.hs-karlsruhe.de/enuw0001/
2JavaServer Pages Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Expressions, scriptlets, declarations, directives
- Including files
- Using Java beans
- XML Syntax
- Combination of Servlets and JavaServer Pages
- Expression language
- Taglibs
- Applets as front ends for Servlets
3JavaServer Pages Installation prerequisites
- Tomcat as the JSP environment
- Tomcat is a powerful JSP environment, which can
be used as a plug-in for many web servers. - Tomcat automatically compiles JSP files during
their first access into servlets and HTML pages. - There are no installation requirements.
- The following code examples assume, that all JSP
files are copied into the directory
ltProjectDirgt/JSP. - The generated servlets for this configuration can
be found in ltProjectDirgt/work/Standalone/localhost
/IP/JSP - After modifying a JSP file, it is not necessary
to restart Tomcat, because Tomcat 5 recognizes
changes in already compiled files and recompiles
them during the first access after the change. - Compilation errors produce error pages, which are
sent back to the client. To see this page, the
"friendly" error messages in Internet Explorer
have to be switched off.
4JavaServer Pages Installation prerequisites
- Eclipse 3 does not support JSP file debugging.
- To debug JSP files use
- JDeveloper 10g (http//technet.oracle.com) ?
249MB. - JBuilder Professional Edition
- Eclipse with WST-Plugin
- In this lecture
- JSP-Specification 2.0
- Examples are tested with Tomcat 5.5.9.
- Expert hints
- Most examples dont work well in distributed
environments. - Most examples dont care about the
synchronization of parallel requests. - Very helpful short syntax overview
- http//java.sun.com/products/jsp/syntax/2.0/card20
.pdf
5JavaServer Pages Idea
- Definition JSP (Java Server Page)
- A JSP is an HTML document with embedded Java
code (scripting code). JSP files are compiled on
demand and translated into Servlets. - The scripting code is executed on the server
side. - Advantages of JSP
- Not limited to a single operating system or web
server. - JSP use Java and the servlet technology. It's not
necessary to learn any new language. - It's not necessary to compile the pages. This is
done during the first access ? A developer should
make the first access to give the user a fast
first access. - JSP pages can be build using any HTML tool.
- JSP pages have the file extension .jsp.
- JSP pages can be installed anywhere in the web
server directories. They can use the same
directories like normal HTML pages.
6JavaServer Pages Simple example
- Simple JSP (SimpleJSP.jsp) Inserting some
information. - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtSimple JSPlt/titlegt
- lt/headgt
- ltbodygt
- lth2gtSimple JSPlt/h2gt
- ltulgt
- ltligtCurrent time lt new javav.util.Date()
gtlt/ligt - ltligtYour hostname lt request.getRemoteHost()
gtlt/ligt - ltligtThe ltCODEgttestParamlt/CODEgt form parameter
- lt request.getParameter("testParam") !
null ? - request.getParameter("testParam")
"ltemgtNot setlt/emgt gt - lt/ligt
- lt/ulgt
- lt/bodygt
- lt/htmlgt
7JavaServer Pages Simple example
8JavaServer Pages Simple example
- Output with parameter set
9JavaServer Pages Differences to servlets
- JavaServer Pages and servlets differ in many
ways - JavaServer Pages are located in "normal" HTML
directories on the server. - They can use relative URLs to access HTML files.
Servlets have their own special directory
mappings. - JSP files can be created using standard web
tools. Only some dynamic content is added. - Servlet files have to write the result using
println methods. There is no tool support
available.
10JavaServer Pages Template text
- Definition Template text
- Template text is the static HTML part of a JSP.
It can be created with any interactive tool. - The biggest parts of JavaServer Pages consist of
static HTML, the template text. - There are two differences between template text
and normal HTML - To create the output lt, in template text lt\ has
to be used. - Two different kinds of comments are supported
11JavaServer Pages JSP-Constructions
- Scripting elements
- JSP scripting elements insert code into the
generated servlet. - Three different types are supported
12JavaServer Pages Expressions
- Definition Expression
- An expression is a piece of Java code which
generates a result during execution. It can be a
constant value, a variable or a method call. The
result is converted into a string and inserted
into the output. - lt Java Expressiongt The evaluated expression
is converted into a string and inserted into the
response. - The expression is evaluated during runtime (the
access of the page). - Expressions have access to all information of the
request (SimpleJSPExpression.jsp). - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
-
- ltligtCurrent time lt new java.util.Date()
gtlt/ligt - lt/ulgt
- lt/bodygt
- lt/htmlgt
13JavaServer Pages Expressions
14JavaServer Pages Expressions Predefined
variables
- To keep the expressions as simple as possible,
several variables are predefined (e.g.) - request The browser request (class
HttpServletRequest). - response The response, which will be send back
to the client (class HttpServletResponse). - session The Servlet session object for session
tracking (class HttpSession). - Example
- Your hostname lt request.getRemoteHost() gt
15JavaServer Pages Scriptlets
- Definition Scriptlet
- A scriptlet is a piece of (complicated) Java
code. It is executed during runtime. - Scriptlets are used, if the problem cannot be
solved by inserting simple output. - Syntax lt Java Code gt
- Scriptlets can contain (nearly) any sequence of
Java source code. - Scriptlets have the same access to the predefined
variables request, response, session, out. - To write some text to the output, the variable
out can be used. - Example
- lt
- int rand Math.random() 12
- out.println("Random value " rand)
- gt
- Scriptlets are used to set response headers or
status codes.
16JavaServer Pages Scriptlets Example
- Browser output without a color parameter
- Browser output with request parameter color
(lightgray)
17JavaServer Pages Scriptlets Example
- Example (BGColor.jsp) Setting the background
color depending on a request parameter. - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtColor Testinglt/titlegt
- lt/headgt
- lt
- String bgColor request.getParameter("bgColor"
) - boolean hasExplicitColor bgColor ! null
- if (!hasExplicitColor)
- bgColor "white"
-
- gt
- ltbody bgcolor"lt bgColor gt"gt
- lth2 align"center"gtColor Testinglt/h2gt
18JavaServer Pages Scriptlets Example
- lt
- if (hasExplicitColor)
- out.println("You supplied an explicit
background color of " - bgColor ".")
- else
- out.println("Using default background color
of white. " - "Supply the bgColor request
attribute to try " - "a standard color, an RRGGBB
value, or to see " - "if your browser supports X11
color names.") -
- gt
- lt/bodygt
- lt/htmlgt
19JavaServer Pages Scriptlets Conditional HTML
code generation
- The background color example has one
disadvantage The HTML body text is created as in
servlets The output is written using the println
method. - Using scriptlets, it's possible to generate HTML
code, which depends on some conditions. - Syntax
- lt if (condition) gt
- HTML code 1
- lt else gt
- HTML code 2
- lt gt
- Depending on the condition, only one of the HTML
code pieces is inserted into the output. - Advantage The HTML code can be created using web
tools - Note The opening and closing braces are
required! - Note gt has to be replaced by \gt in the body.
20JavaServer Pages Scriptlets Conditional HTML
code generation (example)
- Improved code generated of the previous example
(BGColor2.jsp) - lt!-- Unchanged ... --gt
- lt if (hasExplicitColor) gt
- You supplied an explicit background color
of ltbgColorgt. - lt else gt
- Using default background color of white.
- Supply the bgColor request attribute to try
- a standard color, an RRGGBB value, or to
see - if your browser supports X11 color names.
- lt gt
- lt/bodygt
- lt/htmlgt
- The generated HTML page does not differ. But the
second version should be preferred, because the
source code is much easier to create using tools. - Rule Dont create much static HTML with Java.
21JavaServer Pages Scriptlets Conditional HTML
code generation
- Mixing of scriptlets and template text
- lt if (Math.random() lt 0.5) gt
- Have a ltstronggtnicelt/stronggt day!
- lt else gt
- Have a ltstronggtlousylt/stronggt day!
- lt gt
- is transformed into the following servlet code
- if (Math.random() lt 0.5)
- out.println("Have a ltstronggtnicelt/stronggt
day!") -
- else
- out.println("Have a ltstronggtlousylt/stronggt
day!") -
22JavaServer Pages Declarations
- Definition Declaration
- A declaration is used to define fields and
methods in the body of the JSP file. They do not
produce output. - Syntax lt! Java Code gt
- Example A counter, which contains the number of
accesses since the server startup. - lt! private static int accessCount 0 gt
- Accesses to page since server reboot
- lt accessCount gt
- Note for distributed web applications
- Multiple simultaneous accesses to the same JSP or
servlet may be executed on different objects of
the same Servlet class in different JVMs. - Consequence Attributes may not be shared.
23JavaServer Pages Synchronizing concurrent
accesses
- Example of a coming disaster (generation of user
ids) - lt! private static long idNum 0 gt
- lt
- String userID "userID" idNum
- out.println("Your ID is " userID ".")
- idNum
- gt
- Idea Mark a block of code, so that only one
thread t1 can enter this block. All other threads
are blocked until the thread t1 has left the
block. - Solution Java has the construct
synchronized(someObject). - The piece of code can be made thread-safe
- lt! private static int idNum 0 gt
- lt
- synchronized(this.getClass())
- String userID "userID" idNum
- out.println("Your ID is " userID ".")
- idNum
-
- gt
24JavaServer Pages Declarations Example
25JavaServer Pages Declarations Example
- Full example (AccessCounts.jsp), synchronization
is missing - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtJSP Declarationslt/titlegt
- lt/headgt
- ltbodygt
- lth1gtJSP Declarationslt/h1gt
- lt! private static int accessCount 0 gt
- Accesses to page since server reboot
- lt accessCount gt
- lt/bodygt
- lt/htmlgt
26JavaServer Pages Predefined variables (again)
- The following predefined variables are supported
in expressions and scriptlets. - These variables are sometimes called implicit
objects. - JSP declarations can't access predefined
variables. - Predefined variables
27JavaServer Pages Predefined variables (again)
28JavaServer Pages The form params example
revisited
- The following (incomplete) HTML page
(FormParamsJSP.html) is nearly equal to the
FormParams2.html page in the Servlet section. But
instead of calling a Servlet, it calls a JSP
document. - ltform action"http//localhost8088/IP/JSP/FormPa
rams.jsp"gt - lttablegt
- lttrgt
- lttdgtYour namelt/tdgt
- lttdgtltinput type"text" name"name"gtlt/tdgt
- lt/trgt
- lttrgt
- lttdgtYour favorite drink 1lt/tdgt
- lttdgtltinput type"text" name"drink"gtlt/tdgt
- lt/trgt
- lttrgt
- lttdgtYour favorite drink 2lt/tdgt
- lttdgtltinput type"text" name"drink"gtlttdgt
- lt/trgt
- lttrgt
- lttdgtYour favorite drink 3lt/tdgt
- lttdgtltinput type"text" name"drink"gtlttdgt
- lt/trgt
29JavaServer Pages The form params example
revisited
- The result is the following HTML page (with some
contents already filled in)
30JavaServer Pages The form params example
revisited
- The JSP page (FormParams.jsp) is similar to the
Servlet - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtForm Paramslt/titlegtlt/headgt
- lt String drinks request.getParameterValues("
drink") gt - ltbodygt
- lth1gtArray paramslt/h1gt
- ltulgt
- ltligtltstronggtnamelt/stronggtlt
request.getParameter("name")gtlt/ligt - ltligtltstronggtdrinkslt/stronggt
- lt for (int i 0 i lt drinks.length i)
- if (i gt 0) gt
- ,
- lt gt
- lt drinks i gt
- lt gtlt/ligt
- lt/ulgt
31JavaServer Pages The form params example
revisited
32JavaServer Pages JSP directives
- Definition Directive
- A directive can change the structure of a
document. - Three different kinds of JSP directives are
supported - General syntax
- lt_at_ directive attribute"value" gt
- lt_at_ directive attribute1"value1"
- attribute2"value2"
- ...
- attributeN"valueN" gt
33JavaServer Pages JSP page directive
- Attribute values can be set in single quotation
marks instead of double quotation marks. - Quotation marks inside the values have to be
escaped (" ? \", ' ? \'). - The page directive can define the following
attributes (not complete) - import
- contentType
- session
- errorPage
- language
- These attributes are explained in the next
chapters. - Upper- and lowercase characters are distinguished.
34JavaServer Pages JSP page directive import
attribute
- Using the import attribute of the page directive,
other packages are imported into the Servlets
source. - This attribute is evaluated during compile time.
- The following packages are always imported
- java.lang.
- javax.servlet.
- javax.servlet.jsp.
- javax.servlet.http.
- maybe some server specific packages
- Syntax
- lt_at_ page import"package.class" gt
- lt_at_ page import"package.class1"
- ...
- "packageN.classN" gt
35JavaServer Pages JSP page directive import
attribute
- Example
- lt_at_ page import"java.util." gt
- The import attribute is the only page attribute,
which can occur more than once in a document. - The import attribute can occur anywhere in a
document. As a common practice, all imports are
grouped at the start of a document. - Directories for self-defined classes
- To ensure, that the Servlet engine will find
self-defined classes, which are not part of the
package hierarchies java and javax.servlet, these
classes or their jar-files have to be stored in
special directories. - The directories depend on the Servlet engine.
36JavaServer Pages JSP page directive import
attribute
- Remember Tomcat 5.5.x uses the following
directories - ltProjectDirgt/WEB-INF/classes/ This directory
contains any Java class files (and associated
resources) required for by application, including
both Servlet and non-Servlet classes, that are
not combined into JAR files. - Example A Java class named
- com.company.mypackage.MyServlet would need to be
stored in a file named - WEB-INF/classes/com/company/mypackage/MyServlet.c
lass - ltProjectDirgt/WEB-INF/lib/ This directory has
JAR files that contain Java class files (and
associated resources) required by the
application, such as third party class libraries.
- After installing new or changed classes in one of
these directories, the Servlet engine has to be
restarted!
37JavaServer Pages JSP page directive
contentType attribute
- The contentType attribute sets the
Content-Type-Header of the response. This header
contains the MIME-Type of the response contents. - Syntax
- lt_at_ page contentType"MIME-Type" gt
- or
- lt_at_ page contentType"MIME-Type
charsetCharacter-Set" gt - Example
- lt_at_ page contentType"text/plain
charsetISO-8859-1" gt - has the same result as the following scriptlet
- lt response.setContentType(
- "text/plain
charsetISO-8859-1") gt - The default preset content type is "text/html"
with character set "ISO-8859-1" (note Servlets
have the default content type "text/plain").
38JavaServer Pages JSP page directive
contentType attribute (simple example)
- The following JSP document (ContentType.jsp)
returns an HTML page as plain text. Browsers
should show the source code, but the Internet
Explorer interprets the contents and shows the
rendered page. - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtThe contentType Attributelt/titlegt
- lt/headgt
- ltbodygt
- lth2gtThe contentType Attributelt/h2gt
- lt_at_ page contentType"text/plain" gt
- This should be rendered as plain text,
- ltstronggtnotlt/stronggt as HTML.
- lt/bodygt
- lt/htmlgt
39JavaServer Pages JSP page directive
contentType attribute (simple example)
- Browser output (Firefox and Internet Explorer 6)
40JavaServer Pages JSP page directive
contentType attribute (Excel example)
- This example shows the application of the content
type to generate an Excel document. Excel
documents can be written in two easy ways
Returning tabular separated values or returning
an HTML table. Of course, it's also possible to
create Excel's internal file format. - The MIME type for Excel documents is
- "application/vnd.ms-excel".
- Returning tabular separated values (Excel.jsp)
- lt_at_ page contentType"application/vnd.ms-excel"
gt - lt-- Note that there are tabs, not spaces,
between columns. --gt - 1997 1998 1999 2000 2001 (Anticipated)
- 12.3 13.4 14.5 15.6 16.7
41JavaServer Pages JSP page directive
contentType attribute (Excel example)
- If the user confirms to open Excel, the document
is shown
42JavaServer Pages JSP page directive
contentType attribute (Excel example)
- Newer Excel versions are able to interpret simple
HTML tables. This allows a very flexible way to
either display a document using Excel or to
render it in a browser. - The JSP file evaluates the request parameter
format, which can contain the value excel or any
other value. Depending on the value of this
parameter, an Excel or an HTML document is
returned. - The page directive cannot be evaluated during
runtime. It's not possible, to do something like
this - lt String format request.getParameter("format")
- if ((format ! null) (format.equals("excel"))
- gt
- lt_at_ page contentType"application/vnd.ms-excel"
gt - lt gt
- The content will always be Excel.
43JavaServer Pages JSP page directive session
attribute
- The session attribute controls, whether this JSP
document participates in a session or not. - Syntax, two different values are allowed
- lt_at_ page session"true" gt lt!-- Default --gt
- lt_at_ page session"false" gt
- If this attribute is true, the predefined
variable session is bound to an already existing
session. If no session exists, a new session is
created. - If the attribute is false, no session object is
created. Any attempt to access this objects leads
to a compile-time error.
44JavaServer Pages JSP page directive errorPage
attribute (example)
Request
ComputeSpeed.jsp
Ok
Error
SpeedError.jsp
45JavaServer Pages JSP page directive errorPage
attribute
- The attribute errorPage specifies another JSP
file, which will be displayed, if this page
throws an exception. - Syntax
- lt_at_ page errorPage"Relative URL" gt
- The error page can use the predefined variable
exception, which contains the complete exception
object. - Example
- A JSP document (ComputeSpeed.jsp) accepts a
distance and a time parameter to calculate the
resulting speed. The JSP does not test for wrong
or missing parameters. - It defines another JSP document (SpeedErrors.jsp)
for error handling. - This page shows a detailed error message.
46JavaServer Pages JSP page directive errorPage
attribute (example)
- Source code (ComputeSpeed.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtComputing Speedlt/titlegt
- lt/headgt
- ltbodygt
- lt_at_ page errorPage"SpeedErrors.jsp" gt
- lth2gtComputing Speedlt/h2gt
- lt!
- // Note lack of try/catch for NumberFormatExcepti
on if - // value is null or malformed.
- private double toDouble(String value)
- return(Double.valueOf(value).doubleValue())
-
47JavaServer Pages JSP page directive errorPage
attribute (example)
- lt
- double meters toDouble(request.getParameter(
"meters")) - double seconds toDouble(request.getParameter(
"seconds")) - double speed meters / seconds
- gt
- ltulgt
- ltligtDistance lt meters gt meters.lt/ligt
- ltligtTime lt seconds gt seconds.lt/ligt
- ltligtSpeed lt speed gt meters per
second.lt/ligt - lt/ulgt
- lt/bodygt
- lt/htmlgt
48JavaServer Pages JSP page directive errorPage
attribute (example)
- Error page (SpeedErrors.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtError Computing Speedlt/titlegtlt/headgt
- ltbodygt
- lt_at_ page isErrorPage"true" gt
- lth2gtError Computing Speedlt/h2gt
- ltpgt
- ComputeSpeed.jsp reported a computation error!
Please - revisited this page later again.
- lt/bodygt
- lt/htmlgt
- The attribute isErrorPage denotes, that this page
is an error page for other pages. - Syntax, two different values are allowed
- lt_at_ page isErrorPage"true" gt
- lt_at_ page isErrorPage"false" gt lt!-- Default
--gt
49JavaServer Pages Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Expressions, scriptlets, declarations, directives
- Including files
- Using Java beans
- XML Syntax
- Combination of Servlets and JavaServer Pages
- Expression language
- Taglibs
- Applets as front ends for Servlets
50JavaServer Pages Including files
- JSP offers three different ways to include
documents
51JavaServer Pages Including files During
compile-time
- The include directive is used to import files
during compile-time. - Syntax
- lt_at_ include file"Relative URL" gt
- Consequences
- Because the imported files will be compiled, they
can contain JSP elements. The imported files
often contain frequently used components like
contact information, page counters, navigation
bars and much more. - If the imported file changes, all JSPs importing
this page, have to be recompiled. Many Servlet
engines do not support an automated
recompilation, but they may do it ? don't rely on
it (Tomcat 4 and 5 support this).
52JavaServer Pages Including files During
compile-time (example)
- Browser output after the first and following
accesses
53JavaServer Pages Including files During
compile-time (example)
- The following example contains a page fragment
with contact information and a per-page access
counter (ContactSection.jsp) - lt-- The following become fields in each servlet
that - results from a JSP page that includes this
file. --gt - lt!
- private static int accessCount 0
- gt
- ltpgt
- lthrgt
- This page copy 2006
- lta href"http//www.my-company.com/"gtmy-company.co
mlt/agt. - This page has been accessed lt accessCount gt
- times since server reboot.
54JavaServer Pages Including files During
compile-time (example)
- The main page includes the contact section file
(SomeRandomPage.jsp) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtSome Random Pagelt/titlegt
- lt/headgt
- ltbodygt
- lth2gtSome Random Pagelt/h2gt
- ltpgt
- Information about our products and services.
- ltpgt
- Blah, blah, blah.
- ltpgt
- Yadda, yadda, yadda.
- lt_at_ include file"ContactSection.jsp" gt
-
- lt/bodygt
55JavaServer Pages Including files During
access-time
- The jspinclude action inserts pages during
access-time. - Syntax
- ltjspinclude page"Relative URL" flush"true" /gt
- The included files can have any extension.
- If the included file is a JSP
- The included JSP is executed.
- The output of it is inserted into the output of
the main JSP - The included JSP cannot change the status code or
access cookies. - If the included JSP has changed, it is
automatically recompiled.
56JavaServer Pages Including files During
access-time (example)
57JavaServer Pages Including files During
access-time (example)
- Example Displaying some news (WhatsNew.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtWhat's Newlt/titlegt
- lt/headgt
- ltbodygt
- lth2gtWhat's New at JspNews.comlt/h2gt
- ltpgt
- Here is a summary of our four most recent news
stories - ltolgt
- lt for (int i 1 i lt 4 i)
- String file "news/Item" i ".html"
- gt
- ltligtltjspinclude page"ltfilegt"
flush"true" /gtlt/ligt - lt gt
58JavaServer Pages Including files During
access-time (example)
- The included file news/Item1.html
- ltstronggtBill Gates acts humble.lt/stronggt In a
startling and - unexpected development, Microsoft big wig Bill
Gates put on an - open act of humility yesterday.
- lta href"http//www.microsoft.com/Never.html"gtMor
e details...lt/agt - The included file news/Item2.html
- ltstronggtScott McNealy acts serious.lt/stronggt In
an unexpected - twist, wisecracking Sun head Scott McNealy was
sober and subdued - at yesterday's meeting.
- lta href"http//www.sun.com/Imposter.html"gtMore
details...lt/agt - The included file news/Item3.html
- ltstronggtLarry Ellison acts conciliatory.lt/stronggt
Catching his - competitors off guard yesterday, Oracle prez
Larry Ellison - referred to his rivals in friendly and
respectful terms. - lta href"http//www.oracle.com/Mistake.html"gtMore
details...lt/agt - The included file news/Item4.html
- ltstronggtSportscaster uses "literally"
correctly.lt/stronggt In an - apparent slip of the tongue, a commentator was
heard to use the word "literally" when he did
ltemgtnotlt/emgt mean iguratively." - lta href"http//www.espn.com/Slip.html"gtMore
details...lt/agt
59JavaServer Pages Including applets Idea
- Normal applets are includes using the common tag
APPLET. - These applets use JDK 1.1 or 1.02 (the browser
internal runtime engines). - The newer JDKs 1.2 to 1.6 are supported only
using a plug-in. - The plug-in can be downloaded from
http//java.sun.com/products/plugin. - The plug-in is also part of the JDK.
- To use the plug-in for applets, the normal APPLET
tag cannot be used. - JSP has a special element to simplify the
creation of the (complicated) new tag
jspplugin. The server inserts the new applet tag
during page compilation.
60JavaServer Pages Including applets Idea
- Inserting applets (old internal JDK) into a web
page - ltapplet code"MyApplet.class"
- width"475" height"350"gt
- lt!-- Parameters are still missing... --gt
- lt/appletgt
- Using the plug-in inside JSP files, the following
tags must be used - ltjspplugin type"applet" code"MyApplet.class"
- width"475" height"350"gt
- lt!-- Parameters are still missing... --gt
- lt/jspplugingt
- The new tags use XML syntax. As a result, all
tags and their attributes must be written in
lower case letters.
61JavaServer Pages Including applets
Plug-In-Parameters
- The jspplugin element has several parameters.
All values must be quoted!
62JavaServer Pages Including applets
Plug-In-Parameters
63JavaServer Pages Including applets
Applet-Parameters
- Applets can be configured using parameters
(similar to environment variables in normal
applications). - Applets access these parameters using the
getParameter method. - Normal applet parameters (internal JDK)
- ltapplet code"MyApplet.class"
- width"475" height"350"gt
- ltparam name"name1" value"value1"gt
- ltparam name"name2" value"value2"gt
- lt/appletgt
- Using the plug-in inside JSP files, the following
xml-element must be used - ltjspparam name"name1" value"value1" /gt
- The new tags use XML syntax. As a result, all
tags and their attributes must be written in
lower case letters. - All attribute values must be placed inside
quotation marks.
64JavaServer Pages Including applets
Applet-Parameters
- Example
- ltjspplugin type"applet" code"MyApplet.class"
- width"475" height"350"gt
- ltjspparam name"name1" value"value1" /gt
- ltjspparam name"name2" value"value2" /gt
- lt/jspplugingt
- If a browser does not support the generated
object or embed tag, an alternative text can be
shown - ltjspfallbackgt
- HTML code
- lt/jspfallbackgt
- Example
- ltjspplugin type"applet" code"MyApplet.class"
- width"475" height"350"gt
- ltjspparam name"name1" value"value1" /gt
- ltjspfallbackgt
- Your browser does not support the JDK
plug-in! - lt/jspfallbackgt
- lt/jspplugingt
XML syntax!
65JavaServer Pages Including applets
Applet-Parameters
- Created plugin code
- ltobject classid"clsid8AD9C840-044E-11D1-B3E9-00
805F499D93" - width"475" height"350"
- codebase"http//java.sun.com/update/1.5.0/
- jinstall-1_5-windows-i586
.cabVersion1,5,0,0"gt - ltparam name"java_code" value"ParameterApplet.cl
ass"gt - ltparam name"type" value"application/x-java-appl
etversion1.5"gt - ltparam name"name1" value"value1"gt
- ltparam name"name2" value"value2"gt
- ltcommentgt
- ltembed type"application/x-java-appletversion1.
5" width"475" - height"350" pluginspagehttp//java.sun.com/pr
oducts/plugin/ - java_code"MyApplet.class" name1"value1"
name2"value2"/gt - ltnoembedgt
- Your browser does not support the JDK plug-in!
- lt/noembedgt
- lt/commentgt
- lt/objectgt
Internet Explorer
Mozilla
66JavaServer Pages Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Expressions, scriptlets, declarations, directives
- Including files
- Using Java beans
- XML Syntax
- Combination of Servlets and JavaServer Pages
- Expression language
- Taglibs
- Applets as front ends for Servlets
67JavaServer Pages Using Java-Beans Idea
- Problems
- Reusing existing Java code.
- Inserting a lot of Java code into a JSP document
destroys many of the advantages of JSP. - Complex applications should not be coded inside a
JSP. - Sharing information between different requests,
users and/or JSPs. - Solution
- Move most code into Java-Beans.
- JSP documents can access standard Java-Beans.
- This approach keeps JSP files readable for
Web-Designers.
68JavaServer Pages Using Java-Beans Idea
- The action jspuseBean loads a bean into a JSP
document. - Syntax
- ltjspuseBean id"name" class"package.class" /gt
- Example
- ltjspuseBean id"book1" class"hska.faki.servlets
.Book" /gt - jspuseBean seems to be similar to the creation
of an object - ltjspuseBean id"book1" class"hska.faki.servlets
.Book" /gt - This is not equivalent to following scriptlet
- lt hska.faki.servlets.Book book1
- new hska.faki.servlets.Bo
ok() gt - The jspuseBean action is more powerful (e.g. the
bean can have a specified lifetime or can be
shared between different pages). - Consequence jspuseBean generates a reference to
the named object. A new object is created, only
if the named object does not exist. - Java beans have to be installed somewhere in the
regular classpath of the Servlet engine ? see
section about the import attribute of the page
directive.
69JavaServer Pages Using Java-Beans Accessing
bean properties
- Accessing bean properties by jspgetProperty and
jspsetProperty. - Reading a property
- Syntax
- ltjspgetProperty name"beanname"
property"propertyname"/gt - beanname Bean id, set inside the jspuseBean
action. - propertyname Name of the property
- Example
- ltjspgetProperty name"book1" property"title"
/gt - This action is equal to
- lt book1.getTitle() gt
- The XML syntax should be preferred because it's
easier to understand for web designers. - The Java syntax should be used, if the property
is accessed inside a loop or a method.
70JavaServer Pages Using Java-Beans Accessing
bean properties
- Writing a property
- Syntax
- ltjspsetProperty name"beanname"
property"propertyname" - value"propertyvalue" /gt
- beanname Bean name, set inside the jspuseBean
action. - propertyname Name of the property to change
- propertyvalue New value of the property.
- Example
- ltjspsetProperty name"book1" property"title"
- value"Core Servlets and JavaServer
Pages" /gt - This action is equal to
- lt book1.setTitle("Core Servlets and JavaServer
Pages") gt - jspsetProperty is able to convert arguments and
to assign many parameters in one write access ?
will be discussed later. - jspsetProperty can write values during runtime ?
later.
71JavaServer Pages Using Java-Beans Simple
example
- This simple beans stores a message (file
StringBean.java) - package hska.faki
- public class StringBean
- private String message "No message
specified" - public String getMessage()
- return message
-
- public void setMessage(String nMessage)
- message nMessage
-
-
72JavaServer Pages Using Java-Beans Simple
example
- The file is stored together with the class files
in the directory - ltProjectDirgt/WEB-INF/classes/hska/faki.
- Eclipse uses the following directory
- ltProjectDirgt/WEB-INF/src/hska/faki.
- To compile the file outside Eclipse, enter the
directory ltProjectDirgt/WEB-INF/classes and run
the compiler - javac hska/faki/StringBean.java
73JavaServer Pages Using Java-Beans Simple
example
- The JSP document plays with the bean (file
StringBean.jsp) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtUsing JavaBeans with
JSPlt/titlegtlt/headgt - ltbodygt
- lth1gtUsing JavaBeans with JSPlt/h1gt
-
- ltjspuseBean id"info" class"hska.faki.StringBea
n" /gt - ltolgt
- ltligtInitial value (getProperty)
- ltemgtltjspgetProperty name"info"
property"message" /gtlt/emgt - lt/ligt
- ltligtInitial value (JSP expression)
- ltemgtlt info.getMessage() gtlt/emgt
- lt/ligt
- ltligtltjspsetProperty name"info"
property"message" - value"My very best
string bean" /gt - Value after setting property with
setProperty
74JavaServer Pages Using Java-Beans Simple
example
- ltligtlt info.setMessage("Internet
programming") gt - Value after setting property with
scriptlet - ltemgtlt info.getMessage() gtlt/emgt
- lt/ligt
- lt/olgt
-
- lt/bodygt
- lt/htmlgt
- Browser output
75JavaServer Pages Using Java-Beans Defining
bean properties
- Setting bean properties is much more flexible
than a simple method call. jspsetProperty can - evaluate the property name and value during
runtime. - convert String objects into the required data
type of the setter method. - set multiple properties using only a single
command. - Runtime evaluation of properties
- Example
- ltjspsetProperty name"info" property"message"
- value'lt request.getParameter("message
") gt' /gt - Note The value attribute contains double
quotations marks ("). Therefore, the value
attribute uses single quotation marks ('). - Quotation marks inside the value attributes have
to be escaped.
76JavaServer Pages Using Java-Beans Defining
bean properties
- Automatic type conversion
- The following example has a bean with three
properties. Two properties are not String objects
(file SaleEntry.java) - package hska.faki
- / Simple bean to illustrate the various forms
- of jspsetProperty.
- /
- public class SaleEntry
- private int numItems 0
- private double price 0.0
- private String itemID "unknown"
- public int getNumItems()
- return numItems
-
- public void setNumItems(int nNumItems)
- numItems nNumItems
77JavaServer Pages Using Java-Beans Defining
bean properties
- public String getItemID()
- return itemID
-
- public void setItemID(String nItemID)
- itemID (nItemID ! null) ? nItemID
"unknown" -
- public double getPrice()
- return price
-
- public void setPrice(double nPrice)
- price nPrice
-
- public double getTotalCost()
- return price numItems
-
78JavaServer Pages Using Java-Beans Defining
bean properties
- Project (browser output)
- The JSP document reads all request parameters and
stores them in a bean. - During the table creation the JSP retrieves the
bean properties and inserts them into the table.
79JavaServer Pages Using Java-Beans Defining
bean properties
- The following JSP document uses the bean (version
1, stupid solution). It evaluates the request
parameters and enters the values into the bean
(file SaleEntry1.jsp) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtUsing jspsetPropertylt/titlegtlt/headgt
- ltbodygt
- lth1gtUsing jspsetPropertylt/h1gt
- ltjspuseBean id"entry" class"hska.faki.SaleEntr
y" /gt - ltjspsetProperty name"entry" property"itemID"
- value'lt request.getParameter(
"itemID") gt' /gt - lt
- int numItemsOrdered 1
- try
- String numItemsString request.getParameter(
"numItems") - numItemsOrdered Integer.parseInt(numItemsSt
ring) - catch (Exception nfe)
- gt
- ltjspsetProperty name"entry" property"numItems"
- value"lt numItemsOrdered gt"
/gt
80JavaServer Pages Using Java-Beans Defining
bean properties
- lt
- double price 1.0
- try
- String priceString request.getParameter("pr
ice") - price Double.parseDouble(priceString)
- catch (Exception nfe)
- gt
- ltjspsetProperty name"entry" property"price"
- value"lt price gt" /gt
- ltbrgt
- lttable border"1"gt
- lttrgt
- ltthgtItem IDlt/thgtltthgtSingle Pricelt/thgt
- ltthgtNumber Orderedlt/thgtltthgtTotal Pricelt/thgt
- lt/trgt
- lttr align"right"gt
- lttdgtltjspgetProperty name"entry"
property"itemID" /gtlt/tdgt - lttdgtltjspgetProperty name"entry"
property"price" /gtlt/tdgt - lttdgtltjspgetProperty name"entry"
property"numItems" /gtlt/tdgt
81JavaServer Pages Using Java-Beans Defining
bean properties
- Problem Non-String properties.
- Stupid solution
- double price 1.0
- try
- String priceString request.getParameter("pric
e") - price Double.parseDouble(priceString)
-
- catch (Exception ex)
-
- It's not necessary to convert them into the
appropriate data type! - The jspsetProperty action has another attribute
param. - Syntax
- ltjspsetProperty name"entry" property"price
- param"price" /gt
- If the request parameter is available, it is
converted into the required data type. - If the parameter is missing, nothing happens.
82JavaServer Pages Using Java-Beans Defining
bean properties
- The file SaleEntry2.jsp contains a better (but
not perfect) version using the new attribute - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtUsing jspsetPropertylt/titlegtlt/headgt
- ltbodygt
- lth1gtUsing jspsetPropertylt/h1gt
- ltjspuseBean id"entry" class"hska.faki.SaleEntr
y" /gt - ltjspsetProperty name"entry" property"itemID"
- param"itemID" /gt
- ltjspsetProperty name"entry" property"numItems"
- param"numItems" /gt
- ltjspsetProperty name"entry" property"price"
- param"price" /gt
- ...
- The rest of the document is unchanged.
83JavaServer Pages Using Java-Beans Defining
bean properties
- Supported type conversions
84JavaServer Pages Using Java-Beans Defining
bean properties
- Supported type conversions
85JavaServer Pages Using Java-Beans Defining
bean properties
- Custom conversions (only for experts)
- If a Java-Bean has its own beaninfo class with a
custom property editor for a property, this
editor is used to convert the value. - Basic idea
- Given A Java-Bean SaleEntry.
- This class has a beaninfo class
SaleEntryBeanInfo. - The beaninfo class keeps an array of
PropertyDescriptors. - Each PropertyDescriptor defines the behavior of
one property. - The property descriptor can contain a property
editor for a property. - The property editor (class PropertyEditor) has a
method setAsText(String text). - This method is called to convert the String into
the property type.
86JavaServer Pages Using Java-Beans Defining
bean properties
- Often, a bean exists, which stores all request
parameters. - If bean properties and request parameters have
matching names, there is a very comfortable
solution to assign all parameter values to the
bean properties - Syntax
- ltjspsetProperty name"beanname" property"" /gt
- Example
- ltjspsetProperty name"info" property"" /gt
- Warning
- If a parameter is missing, the bean does not
recognize this. There is no assignment of null. - Request parameter names and property names must
match exactly (case sensitive!). - If the request parameter cannot be converted into
the property type, no error is shown. The
property is not changed. Manual conversion is
sometimes better.
87JavaServer Pages Using Java-Beans Defining
bean properties
- The file SaleEntry3.jsp contains the best
solution (without any error handling) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtUsing jspsetPropertylt/titlegtlt/headgt
- ltbodygt
- lth1gtUsing jspsetPropertylt/h1gt
- ltjspuseBean id"entry" class"hska.faki.SaleEntr
y" /gt - ltjspsetProperty name"entry" property"" /gt
- ...
- The rest of the document is unchanged.
88JavaServer Pages Using Java-Beans Sharing beans
- But jspuseBean has an optional scope attribute.
- The value of this attribute defines the lifetime
and the location of the bean object ? see Servlet
chapter - page This is the default value. The bean is
bound to this JSP. - Servlet access pageContext
- The bean dies, when the JSP document is finished,
even if the request is forwarded to another
document. - request The bean is bound to the request. If the
request is forwarded to another document, the
bean does not die. - Servlet access request
- The bean dies, when the request is finished. The
request scope can be used to pass data to a
forwarded document. - Example A Servlet executes complicated requests
and stores the results in the bean object. Then
it calls a JSP document. The JSP reads the bean
properties and generates an output page.
89JavaServer Pages Using Java-Beans Sharing beans
- session The bean is stored in the session object
of this request - Servlet access Session s request.getSession()
- A compilation error occurs, if the session
attribute of the page directive is set to false. - application The bean is stored in the global
Servlet context. All Servlets and JSPs of a web
application share this bean - Servlet access ServletContext ctx
- getServletContext()
- The bean content is destroyed, when the Servlet
engine terminates. - Reading a bean inside a Servlet from the scope
scopeName - Object bean scopeName.getAttribute("beanname")
- Writing a bean into a scope
- scopeName.setAttribute("beanname", beanObject)
90JavaServer Pages Using Java-Beans Conditional
evaluation of bean elements
- Creation
- The action jspuseBean creates a new instance,
only if no instance with the given id and scope
exists. - If the given id and scope exist, only a reference
is returned. - Initialization
- The jspuseBean has an extended syntax
- ltjspuseBean ...gt
- statements
- lt/jspuseBeangt
- The statements are executes only if a new
instance is created. This allows a developer to
initialize a new bean, which is accessed by other
documents. - Solution All documents contain the
initialization code, but the code is executed
only during the bean creation.
91JavaServer Pages Example Survey (Version 4)
- The following application continues the survey
example. - Scenario
JSP Survey4 (entering)
JSP Survey4Collect (collecting)
JSP Survey4Summary (summary)
92JavaServer Pages Example Survey (Version 4)
Session Context
Application Context
Java Bean (Survey4UserAnswer)
Java Bean (Survey4Bean)
read answers
write answers
request start page
Survey4
add to summary
Browser
request collecting page
Survey4Collect
read answer summary
request summary page
Survey4Summary
Servlet engine
93JavaServer Pages Example Survey (Version 4)
Session Context
Application Context
Java Bean (Survey4UserAnswer)
Java Bean (Survey4Bean)
read answers
write answers
request start page
Survey4
add to summary
Browser
request collecting page
Survey4Collect
read answer summary
request summary page
Survey4Summary
Servlet engine
94JavaServer Pages Example Survey (Version 4)
- Bean Survey4Bean (collects a summary of all
answers), incomplete - public class Survey4Bean
- private int poorQuality 0
- private int perfectQuality 0
- private int okDifficulty 0
- private int tooEasyDifficulty 0
-
- // Getter for property "difficulty"
- public int getOkDifficulty()
- return okDifficulty
-
- // Reads the number of answers with quality
"Poor". - public int getPoorQuality()
- return poorQuality
-
- // Reads the number of answers with difficulty
"TooEasy". - public int getTooEasyDifficulty()
- return tooEasyDifficulty
-
95JavaServer Pages Example Survey (Version 4)
- // Adds a new answer to difficulty.
- public void setDifficulty(String answer)
- if (answer.equals("Ok"))
- okDifficulty
-
- if (answer.equals("TooEasy"))
- tooEasyDifficulty
-
-
-
- // Some code removed...
-
96JavaServer Pages Example Survey (Version 4)
Session Context
Application Context
Java Bean (Survey4UserAnswer)
Java Bean (Survey4Bean)
read answers
write answers
request start page
Survey4
add to summary
Browser
request collecting page
Survey4Collect
read answer summary
request summary page
Survey4Summary
Servlet engine
97JavaServer Pages Example Survey (Version 4)
- Bean Survey4UserAnswers (collects answers of a
single user), incomplete - public class Survey4UserAnswers
- private String quality ""
- private String difficulty ""
- public String getDifficulty()
- return difficulty
-
- public String getQuality()
- return quality
-
- public void setDifficulty(String string)
- difficulty string
-
- public void setQuality(String string)
- quality string
-
-
98JavaServer Pages Example Survey (Version 4)
Session Context
Application Context
Java Bean (Survey4UserAnswer)
Java Bean (Survey4Bean)
read answers
write answers
request start page
Survey4
add to summary
Browser
request collecting page
Survey4Collect
read answer summary
request summary page
Survey4Summary
Servlet engine
99JavaServer Pages Example Survey (Version 4)
- JSP Survey4 (creates the start page, fills the
form with previously entered answers),
incomplete - lthtmlgt
- ltheadgtlttitlegtQuestions about Internet programm -
Survey 4lt/titlegt - lt/headgt
- ltjspuseBean id"survey4user" class"hska.faki.Su
rvey4UserAnswers" - scope"session"gt
- ltjspsetProperty name"survey4user"
property"quality" - value"Perfect"/gt
- ltjspsetProperty name"survey4user"
property"difficulty" - value"Ok"/gt
- lt/jspuseBeangt
100JavaServer Pages Example Survey (Version 4)
- ltbodygt
- lth1gtInternetprogramming - Survey 4lt/h1gt
- ltform action"http//localhost8080/IP/JSP/Survey
4Collect.jsp"gt - ltinput type"hidden" name"cmd"
value"collect"gt - lttablegt
- lttrgt
- lt