Version: 1.0
1. JSP Directives
(Directives are used during the translation phase; all otherelements
are used during request processing phase)
1.1. <%@ include
file={static hltml file or regular jsp file} %> ß includes file as part
of thetranslation unit, which is
compiled into a servlet; a page may include multiple includedirectives
1.2. <%@ page{…} %> ß assigns various
page-dependent attributes; defaults are given below
1.2.1. language= “java”
1.2.2. contentType= “text/html”
1.2.3. import=“java.util.Date, java.util.DateFormat” {may have more than one importassignments
via multiple page directives}
1.2.4. session=“true” (if set
to false, the implicit session variable is not available to scripting
elements)
1.2.5. isErrorPage= “false” (set to true
if this page is used as anerror page, and it will
have the implicit exception variable available to scripting elements)
1.2.6. errorPage=“…” (no default;
page-relative or context-relative URI to redirect toin
case exception thrown)
1.2.7. autoFlush=“true” (if false, throws exception when buffer is
full)
1.2.8. buffer=“8kb” (defines
size of buffer; “none” to disable buffering)
1.2.9. info=“…” (no default; used
by server administrative tool as a description ofthe jsp page)
1.2.10. isThreadSafe= “true” (if set to
false, then will useSingleThreadModel)
1.2.11. extends=“…” (no default; fully
qualified classname to extend; class mustimplement JspPage or HttpJspPage interface)
1.3. <%@ taglib {…} %> ß declares a tag library, containing customactions, that is used in the page
1.3.1. prefix= “…” (mandatory; no
default; specifies prefix to use in the action element names for all actions in
thelibrary)
1.3.2. uri=“…” (mandatory; no
default; either a symbolic name for the tag libraryin
the web.xml file or a page- or context-relative uri for the library’sTLD or JAR
file)
2. JSP Scripting Element -
Declaration
2.1. <%! String mystring = new String(“hello”);
%>
2.2. must be avalid java variable declaration; declares instance variables of the JSPimplementation class; thread-safe alternative is to
declare variables inscriptlets, so they are local
variables
2.3. may alsodeclare
methods within a Declaration element
2.4. JSP implicitvariables
are not visible in a declaration element, since they are declaredwithin
the _jspService() method.
3. JSP Scripting Element -
Expression
3.1. <%= 1+2 %> or
<%= mystring %>
3.2. must becomplete
valid java expression that results in or can be converted to a string.
3.3. all JSPimplicit
variables are visible in an expression element
4. JSP Scripting Element - Scriptlet
4.1. <% if (1+2==true) { %> yippee!! <% } else {
%> boohoo!! <% } %>
4.2. scriptletcode fragments are combined
with code for sending template data between them tothe
browser; the combination of all scriptlets in a page
must form valid javacode
4.3. all JSPimplicit
variables are visible in a scriptlet element
5. XML-Based Tags
5.1. Directive: <jsp:directive.{page|include}
attrib= “value” /> ; taglib declared as an xml
namespace, e.g. <jsp:root …xmlns:taglib-prefix=
“uri-of-taglib” … > … </jsp:root>
5.2. Declaration:<jsp:declaration> … </jsp:declaration>
5.3. Expression:<jsp:expression> … </jsp:expression>
5.4. Scriptlet:<jsp:scriptlet>
… </jsp:scriptlet>
6. JSP Action Elements
6.1. <jsp:forward
page= {page- or context-relative uri of jsp or servlet} /> ß uses RequestDispatcher to forward control to another resource; seeRequestDispatcher.forward restrictions
6.2. <jsp:includepage=
{page- or context-relative uri of jsp
or servlet} flush= “true” /> ß uses RequestDispatcher to include outputfrom
another resource; see RequestDispatcher.include
restrictions
6.3. <jsp:useBean{…}
> ß associates a java bean with a name in
one of the JSP scopes and also makes itavailable as a
scripting variable; instantiates the bean if it doesn’talready
exist as the given id
6.3.1. class = {fully qualified
classname for the bean}
6.3.2. id ={java variable name to
use} ß
variable name is made available via <jsp:getProperty..>
as well as a scriptingvariable
6.3.3. scope ={page(default),
request, session or application}ß stores bean object in pageContext, request, session or context attribute,respectively
6.3.4. type ={optional; defines
a type to which the bean should be cast; classmust
be a subclass of type or, if type is an interface, class must implement
type}
6.3.5. beanName ={optional; the beanName parameter as expected by thejava.beans.Beans.instantiate()
method}
6.3.6. Note:jsp:useBean action element can have
a non-empty body, e.g. a jsp:setPropertyaction; the
body will be executed for newly instantiated beans only
6.4. <jsp:setProperty
{…} /> ß sets value of myClock’sproperty(s)
6.4.1. name= “myClock”
6.4.2. property=“date” (if “*”, then will set all properties with names matchingrequest parameters)
6.4.3. param=“…” (optional;
explicitly specifies a request parameter that holdsvalue
to use for specified property)
6.4.4. value=“…” (optional:
explicitly specifies a value to assign to the property;value
cannot be used in conjunction with param;
value can be set equal to an expression e.g. value= “<%= newjava.util.Date()%>”)
6.4.5. ifproperty value is a String, it
is converted to the target property’stype, e.g. Float.valueOf(String)
6.5. <jsp:getProperty name= “myClock”
property= “date” /> ß same as the expression
<%=myClock.date %>
7. JSP Implicit Variables
7.1. request: the HttpServletRequest object for the current request
7.2. response: the HttpServletResponse object for the current request
7.3. session: the HttpSession as per request.getSession();
you may call session.invalidate()to implement a
logout
7.4. application:the ServletContext
as per GenericServlet.getServletContext(); application.log()can be used to write to the application
log file
7.5. out:assigned by web container to a
concrete subclass of JspWriter (which emulatessome of the functionality found PrintWriter
and BufferedWriter, but throwsIOException
unlike PrintWriter)
7.6. exception:only available in error
pages
7.7. config: theServletConfig
as returned by GenericServlet.getServletConfig()ß used by web container
to pass info to servlet or JSP duringinitialization
(e.g init parameters, context, servletname)
7.8. pageContext:used by the container; a pageContext instance provides access to all of thescopes associated with a JSP page, provides access to
several page attributesandall the JSP implicit
variables. A unique instance of this object is created bythe
web container and assigned to the pageContext
variable for each request, andis used in the JSP
implementation class (servlet) to initialize the JSP implicitvariables.
7.9. page:assigned to the instance of the
JSP implementation class (servlet) declared asan Object
8. Custom Action Elements
8.1. Custom actions let you
encapsulate logic and make it available to page authorsin
a familiar format. Using these actions,
the amount of Java code in JSP pagescan be kept to a minimum, making the application easier to debug
and maintain. The steps for creating and using custom actions are as follows:
8.2. Step 1: Develop Tag
Handler Class
8.2.1. A custom action is
basically a bean (specifically, a tag handler class) withproperty
setter methods corresponding to the custom action element’sattributes
(attrib-1..attriib-n).
8.2.2. The taghandler
class must also implement one of two Java interfaces (Tag or BodyTag)
8.2.3. The Tag Interface
8.2.3.1.
The
Tag interface defines the basic protocol between a Tag handler and JSP pageimplementation class. It defines the life cycle and the
methods to be invoked atstart and end tag.
8.2.3.2.
publicvoid setPageContext(PageContext pc) - Called by the page implementation prior todoStartTag() to make the JPS’s PageContext available to the tag handler
8.2.3.3.
publicvoid setParent(Tag
t) - Set the current nesting Tag of this Tag. Called by thepage
implementation prior to doStartTag().
8.2.3.4.
publicTag getParent() -
Returns the current parent
8.2.3.5.
publicint doStartTag()
throws JspException - Process the start tag for this
instance.
8.2.3.5.1.
Returns
SKIP_BODY to skip body evaluation and go next to doEndTag().
8.2.3.5.2.
Returns
EVAL_BODY_INCLUDE to evaluate body into existing outstream
before calling doEndTag() ß only valid when
implementing Tag I/F
8.2.3.5.3.
Returns
EVAL_BODY_TAG to create a BodyContent to process the bodybefore calling doEndTag() ß only valid when
implementing BodyTag I/F
8.2.3.6.
public int doEndTag() throws JspException -
Process the end tag. This method will be called on all Tag objects. You must
implement this at aminimum.
8.2.3.6.1.
Returns
SKIP_PAGE to skip evaluating the rest of the Jsp page
after returningfrom the custom action.
8.2.3.6.2.
Returns
EVAL_PAGE to continue evaluating the rest of the Jsp pageafter returning from the custom action.
8.2.3.7.
public void release() - Called on a Tag handler to
release state for garbagecollection. The page
compiler guarantees this method will be called on all taghandlers,
but there may be multiple invocations on doStartTag
and doEndTag inbetween. release() should
release all objects created by tag handler and thencall
super.release().
8.2.3.8.
Note: The tag handler gets a copy of theJSP’s
PageContext when the implementation calls setPageContext(..)
8.2.3.9.
Note: Call pageContext.getOut() to get
aJspWriter for printing output
8.2.4. The TagSupport
Class
8.2.4.1.
In
order to implement the Tag interface, a class may extend the TagSupportclass, which includes a basic implementation of
the Tag interface. It alsoincludes:
8.2.4.2.
public static final Tag findAncestorWithClass(Tag
from, java.lang.Class klass)
-Returns the nearest ancestor that implements the interface or is an instance ofthe class specified. This class is used for coordination
among cooperating tags.
8.2.5. BodyTag Interface
8.2.5.1.
The
BodyTag interface extends Tag by defining additional
methods that let a Taghandler access its body.
8.2.5.2.
publicvoid setBodyContent(BodyContent b) ß Setter method for the bodyContent property. This method will not be invoked ifthere is no body evaluation.
8.2.5.3.
publicvoid doInitBody()
throws JspException ß The method will be
invoked once per action invocation by the pageimplementation
after setBodyContent() call and before the evaluation
of thetag's body into that BodyContent. This method will not be invoked if there isno body evaluation.
8.2.5.4.
publicint doAfterBody()
throws JspException ß This method is invoked
after every body evaluation. The pair "BODY --doAfterBody()"
is invoked initially if doStartTag() returned
EVAL_BODY_TAG, andit is repeated as long as the doAfterBody() evaluation returns EVAL_BODY_TAG
8.2.6. BodyTagSupport Class
8.2.6.1.
In
order to implement BodyTag, a class may extend the BodyTagSupport class,which
includes a basic implementation of the BodyTag
interface. It alsoincludes:
8.2.6.2.
publicBodyContent getBodyContent()
ß
Get current bodyContent; bodyContent.getString()
will return the bodyevaluation as a String
8.2.6.3.
publicJspWriter getPreviousOut()
ß
Get surrounding out; getPreviousOut().print(getBodyContent().getString()) willprint the body output to the surrounding out.
8.3. Step 2: Support Variable
Declaration via Custom Action
8.3.1. Step A: Place Object in a
Variable Scope ß
The object must be placed in one of the JSPscopes, so
it can be found by findAttribute() in Step B and assigned to the variable.
8.3.1.1.
This
must be done in the tag handler using the setAttribute
method for theappropriate scope object (pageContext, request, session, application)
8.3.2. Step B: The TagExtraInfo Class ß this must be defined in orderfor the container to create and assign a scripting
variable
8.3.2.1.
When
you develop a tag handler for an action that introduces an object, you mustalso create a subclass of the TagExtraInfo
class and override its getVariableInfo() method. The JSP container consults an instance of this
class when it generates the codefor the custom action
by calling its getVariableInfo() method:
8.3.2.2.
publicVariableInfo[ ] getVariableInfo(TagData data)ß returns info on scripting variables
defined by this tag (an array containingone VariableInfo element per scripting variable). Each VariableInfo is createdby new VariableInfo(String id, String classname,
boolean declare, int
scope).scope can be
8.3.2.2.1.
AT_BEGIN
- variable is visible after start tag. Handler must give the variable a value
and save it in one of the JSP scopeswithin the doStartTag()
method, and can also modify the value in doAfterBody().
8.3.2.2.2.
AT_END-
variable is visible after end tag. Handler must make variable visible at thevery latest in the doEndTag
method.
8.3.2.2.3.
NESTED-
variable is visible only within the start/end tags. Handler must make variablevisible in either doStartTag()
or doInitBody(), and can also modify the value indoAfterBody()
8.3.2.3.
The
container passes in as a parameter the translation-time TagData
instance, which holds a list ofattributes accepted by
the custom action.
8.4. Step 3: Create Tag
Library Descriptor (TLD)
8.4.1. An XML file that maps
all custom action names to the corrresponding tag handlerclasses, and describes all attributes supported by
each custom action for syntaxvalidation.
8.4.2. <taglib>
ß
mandatory
8.4.3. <tlibversion>1.0</tlibversion> ß mandatory
8.4.4. <jspversion>1.1</jspversion> ß optional; default is
1.1
8.4.5. <shortname>test</shortname> ß mandatory; used by
authoring tools; indicates the default prefix for the actionelements
8.4.6. <uri>/testlib</uri> ß optional; intended for
use by authoring tools as default value for uriattribute
in a taglib directive
8.4.7. <info> my very first tag library </info> ß optional; to be used by graphical tools
8.4.8. <tag>
8.4.9. <name>hello</name>
8.4.10. <tagclass>testaction.helloworld.HelloWorldTag</tagclass>
8.4.11. <teiclass>testaction.helloworld.HelloWorldTagExtraInfo</teiclass> ß optional
8.4.12. <bodycontent>
{empty or JSP(default) or tagdependent} </bodycontent> ß optional
8.4.13. <info>a tag to say
hello</info> ß optional
8.4.14. <attribute>
8.4.14.1.1.1.
<name>
attriib-1 </name>
8.4.14.1.1.2.
<required>
{true or false(default)} </required>
8.4.14.1.1.3.
<rtexprvalue> {true if expression allowed, orfalse(default)} </rtexprvalue>
8.4.14.1.2.
</attribute>
8.4.15. </tag>
8.4.16. </taglib>
8.5. Step 4: Include a Taglib Directive in the JSP Page
8.5.1. Option 1: <%@ taglib uri= “/WEB-INF/tlds/testlib.tld” prefix= “test” %>
8.5.2. Option 2:<%@ taglib uri= “/WEB-INF/lib/testlib.jar” prefix= “test” %>ß this sets the uri to a JAR file in WEB-INF/lib whichcontains
the TLD file & all class files as follows:
8.5.2.1.
The
tld file must be stored in META-INF directory, and
the class files must be in their package hierarchy
8.5.2.2.
Not
allJSP 1.1 compliant containers support this
notation; so if not supported, extractthe TLD file,
and point directly to it as in Option 1
8.5.3. Option 3: <%@ taglib uri= “/testlib”
prefix= “test” %> ß
this sets the uri to asymbolic
name which is mapped to an actual TLD in the web.xml
file, as follows:
8.5.3.1.
<web-app>
… <taglib>
<taglib-uri>/testlib</taglib-uri><taglib-location>/WEB-INF/tlds/testlib.tld</taglib-location>
</taglib> …</web-app>
8.5.3.2.
This
isuseful when you upgrade to a newer version of a tag
library and want to changethe name of the file for
all JSP pages in one place
8.6. Step 5: Call Custom
Action from JSP Page
8.6.1. <prefix:action
attrib-1=value-1 … attrib-n=value-n> {optional-body} </prefix:action> ß may or may not include
body; body can consistof other custom tags or jsp code
8.6.2. <prefix:action
attrib-1=value-1 … attrib-n=value-n /> ß does not include body
8.7. Step 6: Custom Action
Syntax Validation
8.7.1. During JSP translation
phase, container compares each custom action element to thespecification
of the custom action element in the TLD:
8.7.1.1.
Verifies
that name of custom action matches a name in the TLD for the prefix
8.7.1.2.
Verifiesthat no required attribute
is missing, and that any attribute supplied isspecified
in the TLD
8.7.1.3.
CallsisValid(TagData data) in handler’s TagExtraInfo class to run additionalprogrammer-defined
validation checks, e.g. {if(data.getAttribute(“attrib1”)!=null…)
returnfalse}.
8.8. Step 7: Custom Action
Code Generation
8.8.1. During the JSP
translation phase, custom action calls are converted to codeembedded
within the JSP servlet class as follows:
8.8.1.1.
Instanstiate new tag handler class
8.8.1.2.
setPageContext() and setParent()
8.8.1.3.
setAttribute-1(value-1)
to setAttrbute-n(value-n)
8.8.1.4.
doStartTag()
8.8.1.5.
processbody as follows, but only if there is a body and doStartTag()
returnsEVAL_BODY_TAG
8.8.1.5.1.
setBodyContent(out) - get and
initialize a new BodyContent object (a JspWriter) to capture bodyoutput
8.8.1.5.2.
doInitBody() - prepare for the 1stpass
through the body, perhaps setting scripting variables that are madeavailable to the body
8.8.1.5.3.
doAfterBody() after processing BODY - if returns EVAL_BODY_TAG,then repeat this step; if SKIP_BODY, then
continue to doEndTag()
8.8.1.6.
doEndTag() ß if returns SKIP_PAGE, then return from Jspimplementation class; if returns EVAL_PAGE, then
continue with page evaluation
8.8.1.7.
Repeatstarting at setAttribute
step for additional calls to same custom action usingsame
set of attributes within the same JSP page
8.8.1.8.
Callrelease() after last invocation of custom action
in order to release state
9. JSP Page Lifecycle
9.1. The Translation Phase
includes the following and is initiated either (1) whenthe
first request for a new or updated JSP page is received, or (2) atdeployment time, depending on the application server
9.1.1. Page Translation: The
JSP page is translated into Java servlet code.
9.1.2. JSP PageCompilation:
The servlet code is compiled into a JSP pageimplementation class.
9.2. The Execution /
Request-Processing Phase includes the following and is
the sameas for a regular servlet.
9.2.1. Load Class: The JSP page
implementation class is loaded by the JVM.
9.2.2. CreateInstance: The JSP page
implementation class is instantiated.
9.2.3. CalljspInit: jsp_init() is invoked when the JspPage is initialized. At this pointgetServletConfig() will
return the desired value.
9.2.4. <