scwcd tutorial
TRANSCRIPT
-
8/8/2019 Scwcd Tutorial
1/269
un's Java 2 Web Component Developer Certification
Sun's Java 2 Web Component Developer Certification
Sun's Java 2 Web Component DeveloperCertification
Alx Dark
Copyright 2002 Alx Dark
Revision Hist ory
Revision 1.14 2003-07-08
Minor typographic mistakes corrected, clarifications on relationship of
doGet and doHead methods.
Revision 1.13 2003-01-22
Table of Cont ents
q Preface
q The Servlet Model
q The Structure and Deployment of Modern Servlet Web
Applications
q The Servlet Container Model
q Designing and Developing Servlets to Handle Server-side
Exceptions
q Designing and Developing Servlets Using Session Management
ttp://home.earthlink.net/~alxdark/software/wcd-guide/index.html (1 of 2)9/15/2003 7:10:23 PM
-
8/8/2019 Scwcd Tutorial
2/269
un's Java 2 Web Component Developer Certification
q Designing and Developing Secure Web Applications
q Designing and Developing Thread-safe Servlets
q The Java Server Pages (JSP) Technology Model
q Designing and Developing Reusable Web Components
q Designing and Developing JSP pages Using JavaBean
Componentsq Designing and Developing JSP pages Using Custom Tags
q Designing and Developing a Custom Tag Library
q Design Patterns
q Sources
List of Tables
q 1. Directives
q 1. Attributes
q 1. Classes and Methods Required by Kind of Tag
q 2. Body Content Values
q 3. Tag Interface Lifecycle
q 4. IterationTag Interface Lifecycle
q 5. BodyTag Interface Lifecycle
Pre
ttp://home.earthlink.net/~alxdark/software/wcd-guide/index.html (2 of 2)9/15/2003 7:10:23 PM
http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?- -
8/8/2019 Scwcd Tutorial
3/269
reface
Preface
rev
Preface
Table of Cont ents
q Contributors
q Document Publication and Formats
I prepared this study guide based on Sun's exam objectives for the Web
Component Developer certification. The organization and language of
the objectives document are not ideal. At times that document is
ambiguous. Where necessary, I have looked at the interpretations of
other study guides for clarification. You can find other great resources
for the exam (including free practice exams) at the SCWCD links page
at JavaRanch.
This study guide assumes that you have a strong knowledge of Java
and some familiarity with servlets and JSP, since these are both
necessary before you'd consider taking the exam.
I wrote this guide prior to taking the test and it contains no information
about exam questions. I passed with a 93% using this guide, but of
course, I researched and wrote it (I also rushed to get the certification
before returning to work). While I can't make any claims about this
guide as an aide to your own performance on the exam, I think it is one
of the best study guides currently available.
Be aware that the certification itself does not cover everything in the
ttp://home.earthlink.net/~alxdark/software/wcd-guide/pr01.html (1 of 2)9/15/2003 7:10:24 PM
http://suned.sun.com/US/certification/java/exam_objectives.htmlhttp://www.javaranch.com/scwcdlinks.jsphttp://www.javaranch.com/scwcdlinks.jsphttp://suned.sun.com/US/certification/java/exam_objectives.html -
8/8/2019 Scwcd Tutorial
4/269
reface
servlet 2.3 and JSP 1.2 specifications (e.g., it doesn't cover filters or
some of the newer application-level listeners). The exam doesfocus on
memorizing the APIs of the four packages in the javax.servlet
hierarchy. While you could pass this exam through rote memorization,
that would be the most painful way to do so. I found that the questions
on servlets (my strong suit) were easily answered based on experiencewith the technology.
Alright, enough talk, let's get started!
rev Up
un's Java 2 Web Component Developer
ertificationHome
Contrib
ttp://home.earthlink.net/~alxdark/software/wcd-guide/pr01.html (2 of 2)9/15/2003 7:10:24 PM
-
8/8/2019 Scwcd Tutorial
5/269
The Servlet Model
The Servlet Model
rev
The Servlet Model
Table of Cont ents
q For each of the HTTP methods, GET, POST, and PUT, identify
the corresponding method in the HttpServlet class.
q For each of the HTTP methods, GET, POST, and HEAD, identify
triggers that might cause a browser to use the method, and
identify benefits or functionality of the method.
q For each of the following operations, identify the interface and
method name that should be used:
q Identify the interface and method to access values and resources
and to set object attributes within the following three Web
scopes:q Given a life-cycle method: init, service, or destroy, identify correct
statements about its purpose or about how and when it is
invoked.
q Use a RequestDispatcher to include or forward to a Web
resource
rev Up
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch01.html (1 of 2)9/15/2003 7:10:25 PM
-
8/8/2019 Scwcd Tutorial
6/269
The Servlet Model
ocument Publication and Formats
Home
For each of the HTTP methods, GET, PO
and PUT, identify the corresponding me
in the HttpServlet c
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch01.html (2 of 2)9/15/2003 7:10:25 PM
-
8/8/2019 Scwcd Tutorial
7/269
The Structure and Deployment of Modern Servlet Web Applications
The Structure and Deployment of Modern Servlet Web Applications
rev
The St ruct ure and Deployment of Modern ServletWeb Appl icat ions
Table of Cont ents
q Identify the structure of a Web Application and Web Archive file.
q Match the name with a description of purpose or functionality, for
each of the following deployment descriptor elements:
rev Up
se a RequestDispatcher to include or
rward to a Web resource
HomeIdentify the structure of a Web Applica
and Web Archive
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch02.html9/15/2003 7:10:26 PM
-
8/8/2019 Scwcd Tutorial
8/269
The Servlet Container Model
The Servlet Container Model
rev
The Servlet Container Model
Table of Cont ents
q Identify the uses for and the interfaces (or classes) and methods
to achieve the following features:
q Identify the WebApp deployment descriptor element name that
declares the following features:
q Distinguish the behavior of the following in a distributable:
rev Up
atch the name with a description of purpose
functionality, for each of the following
eployment descriptor elements:
Home
Identify the uses for and the interface
classes) and methods to achieve
following feat
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch03.html9/15/2003 7:10:26 PM
-
8/8/2019 Scwcd Tutorial
9/269
Designing and Developing Servlets to Handle Server-side Exceptions
Designing and Developing Servlets to Handle Server-side Exceptions
rev
Designing and Developing Servlet s t o HandleServer-side Except ions
Table of Cont ents
q Handling Business Logic Exceptions with HTTP Error Codes
q Handling Business Logic Exceptions Other Ways
q Web Application Logs
rev Up
stinguish the behavior of the following in a
stributable:
HomeHandling Business Logic Exceptions
HTTP Error C
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch04.html9/15/2003 7:10:27 PM
-
8/8/2019 Scwcd Tutorial
10/269
Designing and Developing Servlets Using Session Management
Designing and Developing Servlets Using Session Management
rev
Designing and Developing Servlet s Using SessionManagement
Table of Cont ents
q Identify the interface and method for each of the following:
q Given a scenario, state whether a session object will be
invalidated
q URL-rewriting
rev Up
Web Application LogsHome
Identify the interface and method for eac
the follo
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch05.html9/15/2003 7:10:28 PM
-
8/8/2019 Scwcd Tutorial
11/269
Designing and Developing Secure Web Applications
Designing and Developing Secure Web Applications
rev
Designing and Developing Secure Web Appl icat ions
Table of Cont ents
q Identify correct descriptions or statements about the security
issues:
q Identify the deployment descriptor element names, and their
structure, that declare the following:
q Types of authentication
rev Up
RL-rewritingHome
Identify correct descriptions or statem
about the security iss
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch06.html9/15/2003 7:10:28 PM
-
8/8/2019 Scwcd Tutorial
12/269
Designing and Developing Thread-safe Servlets
Designing and Developing Thread-safe Servlets
rev
Designing and Developing Thread-saf e Servlets
Table of Cont ents
q Identify which attribute scopes are thread-safe:
q Multi-threaded and single-threaded servlets
q SingeThreadModel Interface
rev Up
ypes of authenticationHome
Identify which attribute scopes are th
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch07.html9/15/2003 7:10:29 PM
-
8/8/2019 Scwcd Tutorial
13/269
The Java Server Pages (JSP) Technology Model
The Java Server Pages (JSP) Technology Model
rev
The Java Server Pages (JSP) Technology Model
Table of Cont ents
q Write the opening and closing tags for the following JSP tag
types:
q Given a type of JSP tag, identify correct statements about its
purpose or use.
q Given a JSP tag type, identify the equivalent XML-based tags.
q Identify the page directive attribute, and its values, that:
q Identify and put in sequence the following elements of the JSP
page lifecycle:
q Match correct descriptions about purpose, function, or use with
any of the following implicit objects:q Distinguish correct and incorrect scriptlet code for:
rev Up
ngeThreadModel Interface
Home
Write the opening and closing tags fo
following JSP tag ty
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch08.html9/15/2003 7:10:30 PM
-
8/8/2019 Scwcd Tutorial
14/269
Designing and Developing Reusable Web Components
Designing and Developing Reusable Web Components
rev
Designing and Developing Reusable WebComponents
Table of Cont ents
q Given a description of required functionality, identify the JSP
page directive or standard tag in the correct format with the
correct attributes to specify the inclusion of a Web component
into the JSP page.
rev Up
stinguish correct and incorrect scriptlet
ode for:
Home
Given a description of required function
identify the JSP page directive or stan
tag in the correct format with the co
attributes to specify the inclusion of a
component into the JSP p
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch09.html9/15/2003 7:10:31 PM
-
8/8/2019 Scwcd Tutorial
15/269
Designing and Developing JSP pages Using JavaBean Components
Designing and Developing JSP pages Using JavaBean Components
rev
Designing and Developing JSP pages UsingJavaBean Components
Table of Cont ents
q For any of the following tag functions, match the correctly
constructed tag, with attributes and values as appropriate, with
the corresponding description of the tag's functionality:
q JSP/servlet scoped attribute implementations
q Identify techniques that access a declared JavaBean component
rev Up
iven a description of required functionality,
entify the JSP page directive or standard
g in the correct format with the correct
tributes to specify the inclusion of a Web
omponent into the JSP page.
Home
For any of the following tag functions, m
the correctly constructed tag, with attrib
and values as appropriate, with
corresponding description of the t
function
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10.html9/15/2003 7:10:31 PM
-
8/8/2019 Scwcd Tutorial
16/269
Designing and Developing JSP pages Using Custom Tags
Designing and Developing JSP pages Using Custom Tags
rev
Designing and Developing JSP pages Using Cust omTags
Table of Cont ents
q Taglibs in the deployment descriptor
q Taglib directives
q Given a custom tag library, identify properly formatted custom tag
usage in a JSP page. Uses include:
rev Up
entify techniques that access a declared
avaBean componentHome
Taglibs in the deployment desc
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch11.html9/15/2003 7:10:32 PM
-
8/8/2019 Scwcd Tutorial
17/269
Designing and Developing a Custom Tag Library
Designing and Developing a Custom Tag Library
rev
Designing and Developing a Cust om Tag Library
Table of Cont ent s
q Identify the tag library descriptor element names that declare the
following:
q Identify the tag library descriptor element names that declare the
following:
q Given a custom tag, identify the necessary value for the
bodycontent TLD element for any of the following tag types:
q Given a tag event method (doStartTag, doAfterBody, and
doEndTag), identify the correct description of the methods trigger
q Identify valid return values for the following methods:
q
Given a BODY or PAGE constant, identify a correct description ofthe constant's use in the following methods:
q Identify the method in the custom tag handler that accesses:
q Nested tags
I have found the following tables helpful in learning aspects of custom
action programming that are difficult for me to remember. One of my
measurements of a successful software design is its memorability, andby this measure, the javax.servlet.jsp.tagext package is kind
of a mess.
The first table shows, for several different types of tag, the interface or
class you would use to create such a tag, and the methods and
sequence of calls that would be made on that tag handler class. It is
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12.html (1 of 3)9/15/2003 7:10:33 PM
-
8/8/2019 Scwcd Tutorial
18/269
Designing and Developing a Custom Tag Library
based on a table in the J2EE 1.3 tutorial on custom tags, although I
have expanded it:
Table 1. Classes and Methods Required by Kind of Tag
Type Explanation Interface Implementation Method CaSequence
Simple
Contains no
body and
no
attributes.
Tag TagSupport
doStartTag
doEndTag,
release
Attributes
Contains no
body, but
has
attributes.
Tag TagSupport
setAttribu(1..n),
doStartTag
doEndTag,
release
Body, no
interaction
Contains
body
content that
is either
skipped or
evaluated
by JSP
container.
Tag TagSupport
doStartTag
doEndTag,
release
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12.html (2 of 3)9/15/2003 7:10:33 PM
-
8/8/2019 Scwcd Tutorial
19/269
Designing and Developing a Custom Tag Library
Iterative
tag, no
interaction
Contains
body
content
passed to
JSP engine
for
evaluation
one or
more times.
IterationTag TagSupport
doStartTag
doAfterBod
doEndTag,
release
Body,
interaction
Contains a
body that is
processedone or
more times
by the tag
handler.
BodyTag BodyTagSupport
doStartTag
doInitBodydoAfterBod
doEndTag,
release
rev Up
iven a custom tag library, identify properly
rmatted custom tag usage in a JSP page.
ses include:
Home
Identify the tag library descriptor elem
names that declare the follow
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12.html (3 of 3)9/15/2003 7:10:33 PM
-
8/8/2019 Scwcd Tutorial
20/269
Design Patterns
Design Patterns
rev
Design Pat t erns
Table of Cont ents
q Given a scenario description with a list of issues, select the
design pattern that would best solve those issues
q Match design patterns with statements describing potential
benefits that accrue from the use of the pattern, for any of the
following patterns:
rev Up
ested tags
Home
Given a scenario description with a l
issues, select the design pattern that w
best solve those is
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch13.html9/15/2003 7:10:34 PM
-
8/8/2019 Scwcd Tutorial
21/269
ources
Sources
rev
Sources
None of these excellent sources can be blamed for mistakes in this
text--they are my own. Please let me know about them.
Java Servlet Specification 2.3. Sun Microsystems 2001.
JavaServer Pages. Bergsten, Hans. O'Reilly 2002.
JavaServer Pages Specification 1.2. Sun Microsystems 2001.
Sun Certified Web Component Developer Study Guide. Ken Zrobok,
2001?
Web Development with JavaServer Pages. Fields, Duane and Mark
Kolb. Manning, 2000.
rev Up
atch design patterns with statements
escribing potential benefits that accrue from
e use of the pattern, for any of the following
atterns:
Home
ttp://home.earthlink.net/~alxdark/software/wcd-guide/bi01.html9/15/2003 7:10:34 PM
mailto:[email protected]:[email protected] -
8/8/2019 Scwcd Tutorial
22/269
Given a type of JSP tag, identify correct statements about its purpose or use.
Given a type of JSP tag, identify correct statements about its purpose or use.
rev The Java Server Pages (JSP) Technology Model
Given a t ype of JSP t ag, ident i f y cor rectst at ements about i t s purpose or use.
Directives
The specification says directives are "messages to the JSP container."
Among other things, they indicate to the container how to translate a
JSP source file into a servlet source file. The following table
summarizes the available directives:
Table 1. Directives
pageAttributes that apply to the page (and its includes) as awhole. Objective 8.4 discusses specific attributes for this
directive (and there are many).
taglib declares a tag library that will be used in the page.
include
declares a file to be included verbatim at the position of the
directive. Basically a server-side include (the file could be a
fragment). The file is treated as if it had been actually typedinto the page. Contrast this with the include action, where a
request object is handed over to the included resource, and
the outputof that processing is included into the final page.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch08s02.html (1 of 4)9/15/2003 7:10:35 PM
-
8/8/2019 Scwcd Tutorial
23/269
Given a type of JSP tag, identify correct statements about its purpose or use.
Declarations
Discussions of JSP are made more complicated by the fiction that JSP
will be compiled to some other language besides Java. Your JSP will be
compiled into a Java servlet, and a servlet is a class. In that class,
declarations are the code that will be written in the class, rather than inany particular method (particularly the service method and its HTTP
delegates). This can include variable declarations and initializations, or
even whole methods such as jspInit and jspDestroy. They should
be complete code fragments...they are written verbatim to the servlet
class file.
All caveats about the thread safety of instance variables apply.Obviously, this code will be available from other scriptlets or
declarations on the page, which are part of the same class.
Scri pt let s
Again, it's easiest to understand JSP if you think of how JSP elements
are translated into a servlet (although in practice, the actual servlet
generated will include a lot of additional code beyond what is specified
by the developer in a JSP file).
Scriptlets define code fragments that appear in the service method of
the servlet generated from the JSP page (or whatever method
service delegates to). They should be complete language fragments,
although they can be interspersed with the template code that will be
turned into println statements and spit out verbatim (as long as the
resulting mix is syntactically correct code). For example, the following is
legal:
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch08s02.html (2 of 4)9/15/2003 7:10:35 PM
-
8/8/2019 Scwcd Tutorial
24/269
Given a type of JSP tag, identify correct statements about its purpose or use.
Hello
Hello, World!
Because it becomes something close to:
if (request.getAttribute("name") != null) {
out.println("
Hello " + request.getAttribute
("name") + "
");} else {out.println("
Hello, world!
");}
N.B. It's legal, but don't be surprised if your fellow team members
strangle you for this kind of code.
Expressions
The content of an expression tag (which should be an expression) will
be evaluated and the result will be output as a String (with the
toString method or some other conversion routine for primitives). The
expression is evaluated during request processing, not during
translation. If the result cannot be expressed as a String, this will
create a translation error or a runtime ClassCastException,
depending on whether the compiler can catch the error or not.
They are useful because they eliminate the need to use out.println
in your JSP page.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch08s02.html (3 of 4)9/15/2003 7:10:35 PM
-
8/8/2019 Scwcd Tutorial
25/269
Given a type of JSP tag, identify correct statements about its purpose or use.
rev Up
Write the opening and closing tags for the
llowing JSP tag types:
HomeGiven a JSP tag type, identify the equiva
XML-based
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch08s02.html (4 of 4)9/15/2003 7:10:35 PM
-
8/8/2019 Scwcd Tutorial
26/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
For any of the following tag functions, match the correctly constructed tag, with attributes and values a
appropriate, with the corresponding description of the tag's functionality:
revDesigning and Developing JSP pages Using JavaBean
Components
For any of t he following t ag funct ions, match t hecor rect ly const ruct ed t ag, wit h at t r ibut es andvalues as appropri at e, wi t h t he corr espondingdescr ipt ion of t he t ag's f unct ionali t y:
Declare the use of a JavaBean component wi t hin the page.
Here's two examples based on the specification (the specification gives
an example of useBean without a scope attribute, yet it seems to
require the scope attribute in the formal definition of the tag):
In short, this tag attempts to find an existing object with a variable name
equal to the id in the specified scope; if it cannot, it will attempt to create
a variable using these and other attributes. It will place that variable in
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10s01.html (1 of 6)9/15/2003 7:10:36 PM
-
8/8/2019 Scwcd Tutorial
27/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
the appropriate scope and create a variable for scripts on the page. If
there are setProperty tags in the body of the useBean tag, they will
be used to initialize the bean's properties.
Table 1. Attributes
Attribute Rules Comment
id required
Needs to be unique to the page
and a valid variable name.
Identifies an object instance in a
specified scope, and also a
scripting variable declared and
initialized as a reference to that
object (the same thing and a
fine point when the
implementation language is
Java).
scopeoptional, default value
is page
Value can be page, request,
session or application.
class
either class or type
must be present; do not
use beanName if you
do use class
Fully qualified name of the class
that implements this bean.
type
either class or type
must be present; OK to
use beanName if you
use type
The type of the variable to be
created for the page (this might
be a superclass or interface
implemented by the class). If
used without the class or
beanName attributes, the object
must already exist.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10s01.html (2 of 6)9/15/2003 7:10:36 PM
-
8/8/2019 Scwcd Tutorial
28/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
beanNameuse eitherclass or
beanName
The name of a Bean as
expected by the instantiate
() method of the java.beans.
Bean class. Basically a fully-
qualified class name or a
serialized bean. This attribute
can accept a request-time
attribute value.
Speci f y, f or j sp:useBean or j sp:getPropert y t ags, t he name of an
attr ibute.
Apparently by convention rather than requirement, useBean declares a
scoped attribute/variable via its id attribute, while getProperty refers
to that scoped attribute/variable via its name attribute. In the example
below, both of the tags appear on a page in the following order:
...
In this case, a bean is being created/retrieved from the HttpSession
object as someBean, and later being referenced as such in order to
output one of its properties to the screen.
Speci f y, f or a j sp:useBean tag, t he class of t he at t r ibut e.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10s01.html (3 of 6)9/15/2003 7:10:36 PM
-
8/8/2019 Scwcd Tutorial
29/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
Speci f y, f or a j sp:useBean tag, t he scope of t he at t r ibut e.
The example again, this time with the scope attribute. The tag handler
will first look for the userData object in the session-level collection,
then create it if necessary and store it there. It also creates a variable
with the name userData.
Access or mut at e a proper t y f rom a declared JavaBean
The setProperty tag has several variations with different behavior
(all the examples below presume a bean has already been declared):
Sets the specific property of the bean to the indicated value, which can
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10s01.html (4 of 6)9/15/2003 7:10:36 PM
-
8/8/2019 Scwcd Tutorial
30/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
be a request-time attribute value. In addition to setting the bean to any
value, there is support for setting bean properties based on servlet
parameters:
The first version will set the property of the bean to the value of the
(typically HTML form) parameter specified by the param attribute. The
conversion depends on the type of the bean property (e.g. an integer
value will be converted with Integer.parseInt). You can use this
form to map a parameter with a different name to the bean property.
The second version is a shorthand for cases where the parameter is
named identically to the bean property. You needn't specify the
parameter in that situation.
The third version is an even more powerful shorthand that says, "search
through the form parameters, and any time you have a parameter
named after a bean property, use it to set the bean property."
You cannot use both the param and value attributes in the same
setProperty tags.
Specif y, f or a j sp:get Propert y t ag, t he propert y of t he at t r ibute
-
8/8/2019 Scwcd Tutorial
31/269
or any of the following tag functions, match the correctly constructed tag, w...s appropriate, with the corresponding description of the tag's functionality:
property="userType"/>
This tag retrieves the value of the specified property, converts it to a
string (via the toString method), and outputs it to the page (again we
are assuming the bean has already been declared with the useBean
tag).
rev Up
esigning and Developing JSP pages Using
avaBean Components
HomeJSP/servlet scoped attribute implementa
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch10s01.html (6 of 6)9/15/2003 7:10:36 PM
-
8/8/2019 Scwcd Tutorial
32/269
dentify the tag library descriptor element names that declare the following:
Identify the tag library descriptor element names that declare the following:
rev Designing and Developing a Custom Tag Library
Ident i f y t he t ag l ibrary descr ipt or element namest hat declare t he fol lowing:
The name of t he t ag
Warning
The tag library descriptor file has changed in many
minor ways between version 1.1 and 1.2. It would
be easy on the test to remember the old version of
a tag, rather than the newer version. Here's an
entire entry in the TLD file (minus a declaration for
a scripting variable) with the name declaration in
bold:
...
crazyFont
us.alxdark.tags.CrazyFont
us.alxdark.tags.CrazyFontTEI
JSP
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s01.html (1 of 5)9/15/2003 7:10:38 PM
-
8/8/2019 Scwcd Tutorial
33/269
dentify the tag library descriptor element names that declare the following:
Crazy Font
bgcolor
true
true
java.lang.String
The background color as
commonly expressed in
web design: #FFFFFF. Crazy Font will avoid
selecting a random
color that comes too close to the
background color.
Here is the DTD for this tag, which I won't repeat in later sections:
content?,
display-name?, small-icon?, large-icon?,
description?, variable*,
attribute*, example?)>
The class of t he tag handler
...
crazyFont
us.alxdark.tags.CrazyFont
us.alxdark.tags.CrazyFontTEI
JSP
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s01.html (2 of 5)9/15/2003 7:10:38 PM
-
8/8/2019 Scwcd Tutorial
34/269
dentify the tag library descriptor element names that declare the following:
Crazy Font
bgcolor
true
true
java.lang.String
The background color as
commonly expressed in
web design: #FFFFFF. Crazy Font will avoid
selecting a random
color that comes too close to the
background color.
The t ype of cont ent t hat t he t ag accept s
...
crazyFont
us.alxdark.tags.CrazyFont
us.alxdark.tags.CrazyFontTEI
JSP
Crazy Font
bgcolor
true
true
java.lang.String
The background color as
commonly expressed in
web design: #FFFFFF. Crazy Font will avoid
selecting a random
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s01.html (3 of 5)9/15/2003 7:10:38 PM
-
8/8/2019 Scwcd Tutorial
35/269
dentify the tag library descriptor element names that declare the following:
color that comes too close to the
background color.
Table 2. Body Content Values
Label Comment
tagdependent
"The body of the tag is interpreted by the tag
implementation itself, and is most likely in a different
'language', e.g. embedded SQL statements." (JSP 1.2
spec)
JSP
The default value if this tag is not included. "The body
of the tag contains nested JSP syntax." (JSP 1.2 spec).
It can be nothing but template (HTML) text.
empty "The body must be empty" (JSP 1.2 spec).
Any at t ri but es of t he tag
...
crazyFont
us.alxdark.tags.CrazyFont
us.alxdark.tags.CrazyFontTEI
JSP
Crazy Font
images/cfont-small.png
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s01.html (4 of 5)9/15/2003 7:10:38 PM
-
8/8/2019 Scwcd Tutorial
36/269
dentify the tag library descriptor element names that declare the following:
images/cfont-large.png
A sample tag.
bgcolor
true
true
java.lang.StringThe background color as
commonly expressed in
web design: #FFFFFF. Crazy Font will avoid
selecting a random
color that comes too close to the
background color.
This is an example for a human viewer of
the file. Optional.
Wacka
wacka!
rev Up
esigning and Developing a Custom Tag
braryHome
Identify the tag library descriptor elem
names that declare the follow
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s01.html (5 of 5)9/15/2003 7:10:38 PM
-
8/8/2019 Scwcd Tutorial
37/269
dentify valid return values for the following methods:
Identify valid return values for the following methods:
rev Designing and Developing a Custom Tag Library
Ident i f y vali d ret urn values f or t he foll owingmet hods:
doSt ar t Tag, doAf t erBody, doEndTag, PageCont ext .getOut
These return codes determine the order in which these methods are
called, in ways particular to each of the three tag interfaces. The valid
return codes are summarized for each of the interfaces below:
Table 3. Tag Interface Lifecycle
Method Constant Meaning
doStartTag
Tag.SKIP_BODY
If the TLD specifies in a
body-content tag that
the tag is empty, then
doStartTagmustreturn
this value. Proceed to
doEndTag.
Tag.EVAL_BODY_INCLUDEBody is evaluated andpassed through to current
out.
doEndTag
Tag.EVAL_PAGEEvaluate the rest of the
page, as normal.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s05.html (1 of 4)9/15/2003 7:10:39 PM
-
8/8/2019 Scwcd Tutorial
38/269
dentify valid return values for the following methods:
Tag.SKIP_PAGE
Stop processing the page
(e.g. error or forwarding
situation).
Table 4. IterationTag Interface Lifecycle
Method Constant Meaning
doStartTag
Tag.SKIP_BODY
If the TLD specifies in a
body-content tag
that the tag is empty,
then doStartTagmust
return this value.Proceed to doEndTag.
Tag.EVAL_BODY_INCLUDE
Body is evaluated and
passed through to
current out.
doAfterBody
IterationTag.
EVAL_BODY_AGAIN
Evaluate the body
again.
Tag.SKIP_BODY
Do not evaluate body
again. If you want to
skip evaluation of body
entirely, this value must
be returned from
doStartTag. Proceed
to doEndTag.
doEndTag
Tag.EVAL_PAGEEvaluate the rest of the
page, as normal.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s05.html (2 of 4)9/15/2003 7:10:39 PM
-
8/8/2019 Scwcd Tutorial
39/269
dentify valid return values for the following methods:
Tag.SKIP_PAGE
Stop processing the
page (e.g. error or
forwarding situation).
Table 5. BodyTag Interface Lifecycle
Method Constant Meaning
doStartTag
Tag.SKIP_BODY
If the TLD specifies in a
body-content tag that
the tag is empty, then
doStartTagmustreturn
this value. Proceed todoEndTag.
Tag.
EVAL_BODY_INCLUDE
Body is evaluated and
passed through to current
out.
BodyTag.
EVAL_BODY_BUFFERED
Creates a BodyContent
object that captures theprocessing of the body, for
manipulation by the tag
handler.
doInitBody
This method is only called
on tags that implement
BodyTag and that return
EVAL_BODY_BUFFERED
from their doStartTag
method.
IterationTag.
EVAL_BODY_AGAINEvaluate the body again.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s05.html (3 of 4)9/15/2003 7:10:39 PM
-
8/8/2019 Scwcd Tutorial
40/269
dentify valid return values for the following methods:
doAfterBody
Tag.SKIP_BODY
Do not evaluate body
again. If you want to skip
evaluation of body
entirely, this value must be
returned from
doStartTag. Proceed to
doEndTag.
doEndTag
Tag.EVAL_PAGEEvaluate the rest of the
page, as normal.
Tag.SKIP_PAGE
Stop processing the page
(e.g. error or forwarding
situation).
PageContext.getOut returns a JspWriter, although this is not the
full story. When this method is called by a BodyTag handler, or it is
called by a nested tag handler, the actual object may be an instance of
BodyContent, which has methods for accessing the body content after
it has been processed.
rev Up
iven a tag event method (doStartTag,
oAfterBody, and doEndTag), identify the
orrect description of the methods trigger
Home
Given a BODY or PAGE constant, ident
correct description of the constant's us
the following meth
ttp://home.earthlink.net/~alxdark/software/wcd-guide/ch12s05.html (4 of 4)9/15/2003 7:10:39 PM
-
8/8/2019 Scwcd Tutorial
41/269
Contributors
Contributors
rev Preface
Contributors
The following people have contributed corrections, suggestions, etc.:
Jorge Jordao, Amit Ghag, Seenu Maj, Pramila Thakur, Sijtsche
Smeman, and Anthony Beaty.
rev Up
reface Home Document Publication and For
ttp://home.earthlink.net/~alxdark/software/wcd-guide/pr01s01.html9/15/2003 7:10:39 PM
-
8/8/2019 Scwcd Tutorial
42/269
Document Publication and Formats
Document Publication and Formats
rev Preface
Document Publi cat ion and Format s
While the host site for this document may move, the latest version of
this document should always be available at http://purl.org/net/alxdark/
wcd-guide.
You can view the entire guide on one page or on multiple pages if you
wish. You can also download a zip or tar.gz bundle of the guide for
reading off-line.
rev Up
ontributors Home The Servlet M
ttp://home.earthlink.net/~alxdark/software/wcd-guide/pr01s02.html9/15/2003 7:10:40 PM
http://purl.org/net/alxdark/wcd-guidehttp://purl.org/net/alxdark/wcd-guidehttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.ziphttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.tar.gzhttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.tar.gzhttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.ziphttp://purl.org/net/alxdark/wcd-guidehttp://purl.org/net/alxdark/wcd-guide -
8/8/2019 Scwcd Tutorial
43/269
un's Java 2 Web Component Developer Certification
Sun's Java 2 Web Component DeveloperCertification
Alx Dark
Copyright 2002 Alx Dark
Revision Hist ory
Revision 1.14 2003-07-08
Minor typographic mistakes corrected, clarifications on relationship of
doGet and doHead methods.
Revision 1.13 2003-01-22
Table of Cont ent s
q Preface
r Contributors
r Document Publication and Formats
q The Servlet Model
r For each of the HTTP methods, GET, POST, and PUT,
identify the corresponding method in the HttpServlet class.
r For each of the HTTP methods, GET, POST, and HEAD,
identify triggers that might cause a browser to use the
method, and identify benefits or functionality of the
method.
r For each of the following operations, identify the interface
and method name that should be used:
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (1 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
44/269
un's Java 2 Web Component Developer Certification
r Identify the interface and method to access values and
resources and to set object attributes within the following
three Web scopes:
r Given a life-cycle method: init, service, or destroy, identify
correct statements about its purpose or about how and
when it is invoked.r Use a RequestDispatcher to include or forward to a Web
resource
q The Structure and Deployment of Modern Servlet Web
Applications
r Identify the structure of a Web Application and Web
Archive file.
r Match the name with a description of purpose or
functionality, for each of the following deployment
descriptor elements:
q The Servlet Container Model
r Identify the uses for and the interfaces (or classes) and
methods to achieve the following features:
r Identify the WebApp deployment descriptor element name
that declares the following features:
r Distinguish the behavior of the following in a distributable:
q Designing and Developing Servlets to Handle Server-side
Exceptions
r Handling Business Logic Exceptions with HTTP Error
Codes
r Handling Business Logic Exceptions Other Ways
r Web Application Logs
q Designing and Developing Servlets Using Session Management
r Identify the interface and method for each of the following:
r Given a scenario, state whether a session object will be
invalidated
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (2 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
45/269
un's Java 2 Web Component Developer Certification
r URL-rewriting
q Designing and Developing Secure Web Applications
r Identify correct descriptions or statements about the
security issues:
r Identify the deployment descriptor element names, and
their structure, that declare the following:r Types of authentication
q Designing and Developing Thread-safe Servlets
r Identify which attribute scopes are thread-safe:
r Multi-threaded and single-threaded servlets
r SingeThreadModel Interface
q The Java Server Pages (JSP) Technology Model
r Write the opening and closing tags for the following JSP
tag types:
r Given a type of JSP tag, identify correct statements about
its purpose or use.
r Given a JSP tag type, identify the equivalent XML-based
tags.
r Identify the page directive attribute, and its values, that:
r Identify and put in sequence the following elements of the
JSP page lifecycle:
r Match correct descriptions about purpose, function, or use
with any of the following implicit objects:
r Distinguish correct and incorrect scriptlet code for:
q Designing and Developing Reusable Web Components
r Given a description of required functionality, identify the
JSP page directive or standard tag in the correct format
with the correct attributes to specify the inclusion of a Web
component into the JSP page.
q Designing and Developing JSP pages Using JavaBean
Components
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (3 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
46/269
un's Java 2 Web Component Developer Certification
r For any of the following tag functions, match the correctly
constructed tag, with attributes and values as appropriate,
with the corresponding description of the tag's
functionality:
r JSP/servlet scoped attribute implementations
r Identify techniques that access a declared JavaBeancomponent
q Designing and Developing JSP pages Using Custom Tags
r Taglibs in the deployment descriptor
r Taglib directives
r Given a custom tag library, identify properly formatted
custom tag usage in a JSP page. Uses include:
q Designing and Developing a Custom Tag Library
r Identify the tag library descriptor element names that
declare the following:
r Identify the tag library descriptor element names that
declare the following:
r Given a custom tag, identify the necessary value for the
bodycontent TLD element for any of the following tag
types:
r Given a tag event method (doStartTag, doAfterBody, and
doEndTag), identify the correct description of the methods
trigger
r Identify valid return values for the following methods:
r Given a BODY or PAGE constant, identify a correct
description of the constant's use in the following methods:
r Identify the method in the custom tag handler that
accesses:
r Nested tags
q Design Patterns
r Given a scenario description with a list of issues, select the
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (4 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
47/269
un's Java 2 Web Component Developer Certification
design pattern that would best solve those issues
r Match design patterns with statements describing potential
benefits that accrue from the use of the pattern, for any of
the following patterns:
q Sources
List of Tables
q 1. Directives
q 1. Attributes
q 1. Classes and Methods Required by Kind of Tag
q 2. Body Content Values
q 3. Tag Interface Lifecycleq 4. IterationTag Interface Lifecycle
q 5. BodyTag Interface Lifecycle
Preface
Table of Cont ent s
q Contributors
q Document Publication and Formats
I prepared this study guide based on Sun's exam objectives for the Web
Component Developer certification. The organization and language of
the objectives document are not ideal. At times that document is
ambiguous. Where necessary, I have looked at the interpretations of
other study guides for clarification. You can find other great resources
for the exam (including free practice exams) at the SCWCD links page
at JavaRanch.
This study guide assumes that you have a strong knowledge of Java
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (5 of 107)9/15/2003 7:10:50 PM
http://suned.sun.com/US/certification/java/exam_objectives.htmlhttp://www.javaranch.com/scwcdlinks.jsphttp://www.javaranch.com/scwcdlinks.jsphttp://suned.sun.com/US/certification/java/exam_objectives.html -
8/8/2019 Scwcd Tutorial
48/269
un's Java 2 Web Component Developer Certification
and some familiarity with servlets and JSP, since these are both
necessary before you'd consider taking the exam.
I wrote this guide prior to taking the test and it contains no information
about exam questions. I passed with a 93% using this guide, but of
course, I researched and wrote it (I also rushed to get the certification
before returning to work). While I can't make any claims about this
guide as an aide to your own performance on the exam, I think it is one
of the best study guides currently available.
Be aware that the certification itself does not cover everything in the
servlet 2.3 and JSP 1.2 specifications (e.g., it doesn't cover filters or
some of the newer application-level listeners). The exam doesfocus on
memorizing the APIs of the four packages in the javax.servlet
hierarchy. While you could pass this exam through rote memorization,
that would be the most painful way to do so. I found that the questions
on servlets (my strong suit) were easily answered based on experience
with the technology.
Alright, enough talk, let's get started!
Contributors
The following people have contributed corrections, suggestions, etc.:
Jorge Jordao, Amit Ghag, Seenu Maj, Pramila Thakur, Sijtsche
Smeman, and Anthony Beaty.
Document Publi cat ion and Format s
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (6 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
49/269
un's Java 2 Web Component Developer Certification
While the host site for this document may move, the latest version of
this document should always be available at http://purl.org/net/alxdark/
wcd-guide.
You can view the entire guide on one page or on multiple pages if you
wish. You can also download a zip or tar.gz bundle of the guide forreading off-line.
The Servlet Model
Table of Cont ent s
q For each of the HTTP methods, GET, POST, and PUT, identify
the corresponding method in the HttpServlet class.
q For each of the HTTP methods, GET, POST, and HEAD, identify
triggers that might cause a browser to use the method, and
identify benefits or functionality of the method.
q For each of the following operations, identify the interface and
method name that should be used:
q Identify the interface and method to access values and resources
and to set object attributes within the following three Web
scopes:
q Given a life-cycle method: init, service, or destroy, identify correct
statements about its purpose or about how and when it is
invoked.
q Use a RequestDispatcher to include or forward to a Web
resource
For each of t he HTTP met hods, GET, POST, andPUT, ident i f y t he corresponding met hod in t he
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (7 of 107)9/15/2003 7:10:50 PM
http://purl.org/net/alxdark/wcd-guidehttp://purl.org/net/alxdark/wcd-guidehttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.ziphttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.tar.gzhttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.tar.gzhttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide-1.13.ziphttp://purl.org/net/alxdark/wcd-guidehttp://purl.org/net/alxdark/wcd-guide -
8/8/2019 Scwcd Tutorial
50/269
un's Java 2 Web Component Developer Certification
Ht t pServlet class.
HTTP GET
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, java.io.IOException {
...
}
Called by the server to handle a GET request. If you override this
method in HttpServlet to provide functionality, the servlet container
will provide support for the doHead method by calling doGet and
returning only the HttpServletResponse headers (although it
doesn't return the body to the client, it does use it to calculate length
headers).
Generally you use GET for operations that have no side effects, and
that can be safely repeated. For operations like database updates,
POST is the accepted request type.
HTTP POST
protected void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, java.io.IOException {...
}
Called by the server to handle a POST request. An unlimited amount of
information can be sent to the server with such a request, as it is sent in
the body of the request. POST operations typically have side effects,
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (8 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
51/269
un's Java 2 Web Component Developer Certification
and may not be repeatable (updating a database, for example).
HTTP PUT
protected void doPut(HttpServletRequest req,HttpServletResponse res)
throws ServletException, java.io.IOException {
...
}
Called by the server to process a PUT request. It is used to post a file to
the web server. Obviously, the method has side effects.
For each of t he HTTP met hods, GET, POST, andHEAD, ident i f y t r iggers t hat might cause a browsert o use t he met hod, and ident i f y benef i t s orf unct ionali t y of t he met hod.
HTTP GET
GET is used to request a resource, like a file. Browsers can trigger such
a request with a hypertext link; to retrieve a resource that is listed in the
href or src attribute of an element; or if a form either has no action
attribute, or an action value of GET, the browser will use this method to
send form data to the server.
Typically GET is used to retrieve a static resource, although a query
string or extra path information can be appended to the URL of a GET
request in order to trigger server-side processing. Such processing
should not have side-effects and it should be repeatable.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (9 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
52/269
un's Java 2 Web Component Developer Certification
HTTP POST
POST is used to send form data to the server. It can generally only be
triggered by submitting a form that has its method set to the POST
method. A POST can have side-effects and may not be repeatable (for
example, submitting payment for a purchase).
HTTP HEAD
A browser calls a HEAD request when it wants to examine the headers
for a particular resource, such as "Content-Type" or "Content-Length".
Although such a request could be used to examine the document's last
modification time, a browser can also send the "If-Modified-Since"
header in a request, against which the server can compare a resource
and determine whether or not it should send the new version, or a 304
(Not Modified) status code. This feature works with the browser's
caching ability to reduce downloads. HTTP servlets that support GET
requests can implement the getLastModified method to support this
feature (otherwise the servlet will always appear modified and its
content body will always be returned).
For each of t he fol lowing operat ions, ident i f y t heint er face and method name t hat should be used:
Retr ieve HTML form paramet ers fr om t he request
public interface javax.servlet.ServletRequest {
public String getParameter(String name);
public java.lang.String[] getParameterValues
(String name);
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (10 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
53/269
un's Java 2 Web Component Developer Certification
public java.util.Enumeration getParameterNames
();
public java.util.Map getParameterMap();
}
The obvious and easy way to retrieve a value is req.getParameter
("myValue"). The more robust version of this method is
getParameterValues which returns all the values for that key (in
HTTP form data there can be more than one); the getParameter
method will only return the first value if there is more than one.
Where values are sent both in the query string and in the body of the
HTTP request, the values are all added into the collection of parametersavailable through this API; the query string parameters will appear first
in the collection.
Note
The parameter API could be used for other
protocols than HTTP; it is defined in the
ServletRequest interface.
Where you do not know the parameters in advance,
getParameterNames can be helpful. It is most often used for
debugging. The final method returns a Map interface (see the
Collections Tutorial by Sun).
Ret ri eve a servl et init ial izat ion paramet er
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (11 of 107)9/15/2003 7:10:50 PM
http://java.sun.com/docs/books/tutorial/collections/interfaces/map.htmlhttp://java.sun.com/docs/books/tutorial/collections/interfaces/map.htmlhttp://java.sun.com/docs/books/tutorial/collections/interfaces/map.htmlhttp://java.sun.com/docs/books/tutorial/collections/interfaces/map.html -
8/8/2019 Scwcd Tutorial
54/269
un's Java 2 Web Component Developer Certification
public interface javax.servlet.ServletConfig {
public String getInitParameter(String name);
public java.util.Enumeration
getInitParameterNames();
}
Self explanatory. These initialization parameters are set in the
deployment descriptor.
Retrieve HTTP request header information
public interface javax.servlet.http.
HttpServletRequest {
public String getHeader(String name);
public java.util.Enumeration getHeaders(String
name);
public java.util.Enumeration getHeaderNames();
public long getDateHeader(String name);
public int getIntHeader(String name);
}
There are special methods for retrieving headers that are dates or
integers. They throw IllegalArgumentException and
NumberFormatException respectively, if they are called on headers
that cannot be converted to these formats. If these accessor methods
are called on a header that doesn't exist, they return null or -1
depending on the return type. Finally, there is a method for getting a
header that is set multiple times in the request, and for getting all the
header names in the request (e.g. "Cache-Control"). The last is useful
for debugging and reporting.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (12 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
55/269
un's Java 2 Web Component Developer Certification
Set an HTTP response header ; set t he cont ent t ype of t he response
public interface javax.servlet.http.
HttpServletResponse {
// Can be used to test if a header has alreadybeen set
public boolean containsHeader(String name);
// Mutator methods
public void setHeader(String name, String
value);
public void setIntHeader(String name, int
value);
public void setDateHeader(String name, longvalue);
}
public interface javax.servlet.ServletResponse {
public void setContentType(String type);
}
}
Analogous to the access methods, there are special methods for setting
headers that represent integer and date values.
setContentType takes a String value that consists of two parts: a
MIME type, followed by an optional encoding (with the two separated by
a semicolon). Examples include "text/plain" and "text/html; UTF-8". You
have to set the content type prior to getting the PrintWriter for the
response.
Acquire a t ext st ream for t he response
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (13 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
56/269
un's Java 2 Web Component Developer Certification
public interface javax.servlet.ServletResponse {
public java.io.PrintWriter getWriter();
}
Prior to calling this method, you may set the encoding of the
PrintWriter by calling the setContentType method with a Stringargument that includes the mime type and optionally, an encoding to
use (e.g. "text/plain; UTF-8"). You can send a response to the client
with either the PrintWriter or the ServletOutputStream provided
by the getOutputStream method, but you cannot use both. An
attempt to do so will throw an IllegalStateException. Calling
flush on the PrintWriter will commit the response.
Acquire a binary st ream for t he response
public interface javax.servlet.ServletResponse {
public javax.servlet.ServletOutputStream
getOutputStream();
}
You can send a response to the client with either the
ServletOutputStream or the PrintWriter provided by the
getWriter method, but you cannot use both. An attempt to do so will
throw an IllegalStateException. Calling flush on the
ServletOutputStream will commit the response.
Redirect an HTTP request t o another URL
public interface javax.servlet.http.
HttpServletResponse {
public void sendRedirect( String location );
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (14 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
57/269
un's Java 2 Web Component Developer Certification
}
Sends a temporary redirect (HTTP code 307) to the browser with a
Location header directing the browser to a new URL.
The method accepts a relative URL (the container generates the
necessary absolute URL). One might expect that an URL beginning with
a slash (e.g. "/alxdark/test.html") would be mapped relative to the
context path of the web application, but it is not, it is mapped from the
server root. Calling this method after committing part of the response
will throw an IllegalStateException.
The URL string passed to this method can and probably should be
passed through another HttpServletResponse method,
encodeRedirectURL, in order to support URL rewriting where
sessions are required and cookies are disabled:
res.sendRedirect( res.encodeRedirectURL( "../etc/
second.html" ) );
Ident i f y t he int er face and met hod t o access valuesand resources and t o set obj ect at t r ibut es wi t hint he following t hree Web scopes:
Request
public interface javax.servlet.ServletRequest {
public Object getAttribute( String name );
public java.util.Enumeration getAttributeNames
();
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (15 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
58/269
un's Java 2 Web Component Developer Certification
public void setAttribute( String name, Object
object );
public void removeAttribute( String name );
public ServletInputStream getInputStream();
public BufferedReader getReader();
}
There's very little remarkable about these methods. The
ServletRequest object has a collection associated with it. If you pass
a null reference to an object in the setAttribute method, it's the
equivalent of calling removeAttribute with the same name
argument. If there are no attributes, getAttributeNames will return
an empty Enumeration.
As the objectives also mention resources, note that the body of the
request can be retrieved as a binary stream or a character stream using
the getInputStream and getReader methods, respectively.
Session
public interface javax.servlet.http.HttpSession {
public Object getAttribute( String name );
public java.util.Enumeration getAttributeNames
();
public void setAttribute( String name, Object
object );
public void removeAttribute( String name );}
The HttpSession object has a collection associated with it. If you
pass a null reference to an object in the setAttribute method, it's
the equivalent of calling removeAttribute with the same name
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (16 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
59/269
un's Java 2 Web Component Developer Certification
argument. If there are no attributes, getAttributeNames will return
an empty Enumeration.
Context
public interface javax.servlet.ServletContext {
public Object getAttribute( String name );
public java.util.Enumeration getAttributeNames
();
public void setAttribute( String name, Object
object );
public void removeAttribute( String name );
public URL getResource( String path );public InputStream getResourceAsStream( String
path );
}
The ServletContext object has a collection associated with it. If you
pass a null reference to an object in the setAttribute method, it's
the equivalent of calling removeAttribute with the same name
argument. If there are no attributes, getAttributeNames will return
an empty Enumeration.
As far as accessing resources, the ServletContext object provides
two invaluable methods, getResource and getResourceAsStream,
which provide access to any resource (file) in the web application. The
path must begin with a "/" and it is interpreted relative to the context root
of the application (you can access files in the META-INF/ and WEB-
INF/ directories with these methods).
Given a l i f e-cycle met hod: ini t , service, or
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (17 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
60/269
un's Java 2 Web Component Developer Certification
dest roy, ident i f y cor rect st atement s about i t spurpose or about how and when i t is invoked.
init
The init method is called on a servlet instance right after it has been
initialized (the servlet container calls a zero-argument constructor). The
method can be overridden in a subclass to provide one-time
initialization of the servlet (e.g. reading in properties from a properties
file). If for some reason this initialization fails, you should throw an
UnavailableException (note that this exception can take an int
argument specifying how long the server should wait before attempting
to instantiate the servlet again). If the init method does not completesuccessfully, the servlet is not brought into service.
service
Once a servlet is successfully put into service, the service method is
called each time a request is processed by the servlet. This can happen
concurrently from multiple threads, unless the servlet implements the
SingleThreadModel tag interface.
destroy
Once all pending service requests have exited the service method,
the destroy method can be invoked just before a servlet is taken out
of service by the servlet container (dereferenced and garbage-
collected). It is similar to the finalize method available to all Java
objects, and you would use it to release resources, save state
information, and the like.
When will a servlet will be taken out of service? This depends on the
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (18 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
61/269
un's Java 2 Web Component Developer Certification
servlet container, although shutting the container down is surely one
case where all active servlets will be taken out of service.
Use a Request Dispat cher t o include or forward t o
a Web resource
Getting theRequestDispatcher
The ServletContext interface provides two methods to acquire a
RequestDispatcher:
public interface javax.servlet.ServletContext {
public javax.servlet.RequestDispatcher
getRequestDispatcher(String url);
public javax.servlet.RequestDispatcher
getNamedDispatcher(String name);
}
getRequestDispatcher takes an url argument that must begin with
a "/" and represents a path within the current servlet context. The
getNamedDispatcher method allows you to use the name of a
servlet as defined in the deployment descriptor. This approach provides
some additional flexibility as you can re-arrange application components
at a later time.
Note
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (19 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
62/269
un's Java 2 Web Component Developer Certification
Previous versions of this study guide described
getRequestDispatcher as a method to
dispatch across contexts; this is not correct (thanks
to Jorge Jordao for pointing this out).
You can also use a relative path to obtain a getRequestDispatcher
through the use of another method on the request object:
public interface javax.servlet.ServletRequest {
public javax.servlet.RequestDispatcher
getRequestDispatcher(String url);
}
The path provided to this method is relative to the calling servlet.
Query strings can be appended to the URLs provided to these methods;
these additional parameters will be available in the request object'sparameter collection (where they appear first in the collection before
other parameters). However, they fall out of scope after the include or
forward call.
Using t heRequestDispatcher
The code for using a RequestDispatcher is straightforward:
// Just for the sake of illustration
req.setAttribute("us.alxdark.myApp", someObj);
// Get dispatcher with a relative URL
RequestDispatcher dis = req.getRequestDispatcher
("../someUrl.html");
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (20 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
63/269
un's Java 2 Web Component Developer Certification
// include
dis.include(req, res);
// or forward
dis.forward(req, res);
When using the include method, the called servlet can only alter the
body of the response, and not the headers. The path information of the
request also continues to reflect the original request location.
When using the forward method, no content may have been
committed to the client, but the called servlet can adjust the headers as
well as the body of the response (content produced up to the forward
call is cleared from the buffer). The path information of the request isaltered to reflect the location of the called servlet, and no further output
can occur after returning from a forward call (the output is committed
upon returning from the call).
Warning
RequestDispatcher objects obtained with the
getNamedDispatcher method behave differently
than other such objects. As discussed here,
forward calls do not involve an adjustment of the
object's parameters to reflect the path of the called
servlet.
The St ruct ure and Deployment of Modern ServletWeb Appl icat ions
Table of Cont ent s
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (21 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
64/269
un's Java 2 Web Component Developer Certification
q Identify the structure of a Web Application and Web Archive file.
q Match the name with a description of purpose or functionality, for
each of the following deployment descriptor elements:
Ident i f y t he st ruct ure of a Web Appli cat ion andWeb Archive f i le.
Web archive files (jar files with the .war file extension) contain certain
standard directories and files. If you decompress a web application
packaged as antwerp.war, you will at least see the following
directories and files:
index.html
[etc.]
images/
[etc.]
META-INF/
MANIFEST.MF
WEB-INF/
classes/
lib/
web.xml
The root directory can contain any files or folders that compose the web
site, such as images, HTML and/or JSP pages. There are also two
additional folders, META-INF/ and WEB-INF/, that are not directly
accessible to web browsers (the servlet container will not directly serve
files in these folders, but they are still accessible to the developer
through the getResource and getResourceAsStreammethods of
the ServletContext interface).
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (22 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
65/269
un's Java 2 Web Component Developer Certification
The META-INF/ folder serves exactly the same purpose and function
as it does in any other jar file.
The web application deployment descriptor file is named web.xml and
it is located in the WEB-INF/ directory. Jar files (including custom tag
library jar files) are located in a lib/ directory, while other code filessuch as servlets are located in a classes/ directory. These last two
directories are a well-known Java convention, but their location under
the WEB-INF/ directory is unique to web applications.
Custom tag libraries have their own deployment descriptor called a Tag
Library Descriptor (a .tld file). You have some options about where to
place the TLD file as well as the tag class files. Unbundled, you canplace the TLD file anywhere in the WEB-INF/ directory, and then
reference it directly in a taglib directive:
You can also map the URI declared in the taglib directive to an actual
directory path using a declaration in the web.xml file. Here's a sample
declaration in a JSP page:
And how it would be mapped to an actual file:
/my-tags
/WEB-INF/tlds/my-tags.tld
-
8/8/2019 Scwcd Tutorial
66/269
un's Java 2 Web Component Developer Certification
taglib-location>
In addition, custom tag libraries can be bundled as JAR files. In this
case, the TLD file must be located in the WEB-INF/ directory of the jar
file. In the taglib directive, the URI attribute points to the jar file just as
you would include a jar file on your classpath (e.g. /WEB-INF/lib/
myTags.jar).
Mat ch t he name wit h a descr ipt ion of purpose orf unct ionali t y, f or each of t he foll owingdeployment descr ipt or elements:
Servl et inst ance
All of 2.2 discusses the declaration of a servlet and a servlet mapping in
the deployment descriptor file. Here's an example using most of the
elements of the declaration:
test
Test Servlet
A test servlet for illustration
purposes. us.alxdark.test.TestServlet
name
Alx
1
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (24 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
67/269
un's Java 2 Web Component Developer Certification
...
test
/test/*
...
PHBs at the company.
manager
The servlet tag serves four purposes:
1. It describes meta-data for manipulating the servlet in a
development environment, and for loading the servlet in a servlet
container;
2. It provides a name for the servlet that is unique to the application
(and it can make different instances of the same servlet class
available under different names);
3. It provides initialization parameters that can be changed without
recompiling the servlet;
4. It allows the developer to declare information about the security
model to be used when running the servlet.
The DTD for the servlet tag includes many other optional elements:
name?, description?,
(servlet-class|jsp-file), init-param*, load-on-
startup?, run-as?,
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (25 of 107)9/15/2003 7:10:50 PM
-
8/8/2019 Scwcd Tutorial
68/269
un's Java 2 Web Component Developer Certification
security-role-ref*)>
Servlet name
...
test
us.alxdark.test.TestServlet
...
The logical name for the servlet allows you to decouple references to a
servlet from its implementation class. For example, you can acquire a
RequestDispatcher via the logical name of a servlet or JSP page.
Later, if you need to change the class of the servlet, you can simply
adjust the deployment descriptor and avoid changing your
RequestDispatcher code.
pattern)>
Servlet class
...
test
us.alxdark.test.TestServlet
...
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (26 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
69/269
un's Java 2 Web Component Developer Certification
The class declaration specifies the implementing servlet for this
declared servlet instance. It's a string that declares the fully-qualified
name of a class implementing the Servlet interface.
Init iali zat ion paramet ers
dbConnections
10
Number of connectionsmaintained by the DB connection
pool. The default is 10.
...
name
Alx
...
Any number of initialization parameters can be declared for the
application/context as a whole, or for any individual JSP/servlet. The
context-param tag occurs near the top of the deployment descriptor
and describes parameters for the application. Within the servlet tag
there is an init-param tag that serves the same purpose. The values
can be retrieved using the following methods (note that
GenericServlet and HttpServlet implement the ServletConfig
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (27 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
70/269
un's Java 2 Web Component Developer Certification
interface):
public String ServletContext.getInitParameter
(String name);
public Enumeration ServletContext.
getInitParameterNames();
public String ServletConfig.getInitParameter
(String name);
public Enumeration ServletConfig.
getInitParameterNames();
These parameters allow an administrator or deployment developer to
change specific values in the application even after it is compiled and
packaged. This allows for a certain amount of customization after
development.
URL to named servlet mapping
...
test
/test/*
The URL to servlet mapping allows you to decouple references to a
servlet from a specific URL. Instead you can declare that a servlet
should handle requests directed to any page, directory or file type in the
application. The benefits are obvious enough, but the mapping rules are
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (28 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
71/269
un's Java 2 Web Component Developer Certification
somewhat complex.
1. Page mappings include the entire URL, as so: /somepath/
thispage.html;
2. Path mappings are specified as so: /somepath/*;
3. File type/extension mappings are mapped as so: *.ext
4. A default servlet for the application is indicated with the /
mapping.
A request URL (minus the context path and everything to the left of it) is
evaluated by each of the following rules, in order, until a match is made:
1. If there's an exact match, it is selected;
2. Working up the directories specified by the mapping, attempt to
match against a mapping (such that the longest mapping that
applies will be selected);
3. If this doesn't work, and the mapping has an extension mapping
(e.g. *.jsp), use the servlet assigned to that extension;
4. If there is still no match, attempt to use a default servlet for
handling such requests (e.g. a servlet that returns the file at that
physical directory location, if it exists).
These mappings are tricky (at least to my mind) because they are
different than how web servers resolve similarly ambiguous URL paths.
I suggest a review of the servlet 2.3 specification, page 77, where
examples of these mappings are given.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (29 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
72/269
un's Java 2 Web Component Developer Certification
The Servlet Cont ainer Model
Table of Cont ent s
q Identify the uses for and the interfaces (or classes) and methods
to achieve the following features:
q Identify the WebApp deployment descriptor element name that
declares the following features:
q Distinguish the behavior of the following in a distributable:
Ident i f y t he uses f or and t he inter faces (orclasses) and methods t o achieve t he f ollowingfeatures:
Servl et cont ext init ial izat ion paramet ers
public String ServletContext.getInitParameter
(String name);public Enumeration ServletContext.
getInitParameterNames();
Any number of initialization parameters can be declared for the
application/context as a whole. Servlet implementations based on
GenericServlet or HttpServlet implement the ServletConfig
interface, so they can simply call getServletContext() to access
these methods.
These parameters allow an administrator or deployment developer to
change specific values in the application even after it is compiled and
packaged. This allows for a certain amount of customization after
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (30 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
73/269
un's Java 2 Web Component Developer Certification
development. A typical example is setting the number of connections to
be maintained by a database pool.
Servlet cont ext li st ener
public interface javax.servlet.
ServletContextListener {
public void contextDestroyed
(ServletContextEvent sce);
public void contextInitialized
(ServletContextEvent sce);
}
A servlet context listener is declared in the deployment descriptor. You
might use this listener to log on to a database and store a connection as
a servlet context attribute. When the context is destroyed, the
connection could be closed. The event passed to the listener provides a
method for obtaining a reference to the ServletContext that has
started or stopped:
public class javax.servlet.ServetContextEvent {
public ServletContext getServletContext();
}
Servl et cont ext at t ri but e li st ener
public interface javax.servlet.
ServletContextAttributeListener {
public void attributeAdded
(ServletContextAttributeEvent e);
public void attributeRemoved
(ServletContextAttributeEvent e);
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (31 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
74/269
un's Java 2 Web Component Developer Certification
public void attributeReplaced
(ServletContextAttributeEvent e);
}
This listener must be registered in the deployment descriptor. An
example of its use might be to implement a class that logs the additionor removal of database connections to the servlet context attribute
collection. The event passed to this listener provides the ability to get
the servlet context, the attribute name and the object that was involved
in the event:
public class javax.servlet.
ServetContextAttributeEvent
extends ServetContextEvent {
public ServletContext getServletContext();
public String getName();
public Object getValue();
}
Session at t r ibute li st eners
public interface javax.servlet.http.
HttpSessionAttributeListener {
public void attributeAdded
( HttpSessionBindingEvent se );
public void attributeRemoved
( HttpSessionBindingEvent se );public void attributeReplaced
( HttpSessionBindingEvent se );
}
An example of the use of this interface would be an object that kept
track of the names of users who were logged in to an application (as
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (32 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
75/269
un's Java 2 Web Component Developer Certification
measured by active sessions). The event passed to this listener
provides the ability to get the session, the attribute name and the object
that was involved in the event:
public class javax.servlet.http.
HttpSessionBindingEvent
extends HttpSessionEvent {
public String getName();
public Object getValue();
public HttpSession getSession();
}
Warning
There are other listeners that are not mentioned in
the objectives document. They are the
HttpSessionListener, the
HttpSessionActivationListener and the
HttpSessionBindingListener interfaces. If I
remember correctly, these interfaces are
referenced during exam questions about distributed
applications; you'd best be familiar with them if only
to differentiate them from the interfaces covered by
the exam.
Ident i f y t he WebApp deployment descr ipt orelement name that declares the following features:
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (33 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
76/269
un's Java 2 Web Component Developer Certification
Servl et cont ext init ial izat ion paramet ers
dbConnections10
# connections in DB connection
pool.
us.alxdark.test.
LogDbConnections
Here's the DTD for this portion of the deployment descriptor:
Servlet cont ext li st eners, servlet cont ext at t r ibut e list eners, session
li st eners or session at t r ibute list eners
dbConnections
10
# connections in DB connection
pool.
ttp://home.earthlink.net/~alxdark/software/wcd-guide/wcd-guide.html (34 of 107)9/15/2003 7:10:51 PM
-
8/8/2019 Scwcd Tutorial
77/269
un's Java 2 Web Component Developer Certification
us.alxdark.test.
LogDbConnections
List the listeners in the order in which they are to be notified of an event.
The declaration in web.xml is identical for all of the following four
listeners: ServletContextListener,
ServletContextAttributeListener, HttpSessionListener,
HttpSessionAttributeListener.
The DTD for this simple element is:
Dist inguish t he behavior of t he following in adistributable:
Servl et cont ext init ial izat ion paramet ers
The parameters are local to the virtual machine (VM) in which they are
created. If information needs to be shared between servlets in adistributed environment, it should be placed in a session (which
migrates with the user between servers), or a store such as a database,
EJB, or directory service.
Servlet cont ext li st ener
ttp://home.earthli