Java Server Pages JSP - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Java Server Pages JSP

Description:

iterations have terminated) and returns an int with value : ... An iterating tag :- br demo:iter Here is some content br Today is %= (new Date()) % br ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 28
Provided by: petem7
Category:
Tags: jsp | iterating | java | pages | server

less

Transcript and Presenter's Notes

Title: Java Server Pages JSP


1
Java Server Pages (JSP)
The life cycle of a JSP page is as follows -
On first request, web-container compiles
page into a Servlet. It then calls the
method void jspInit() which can be overridden to
provide custom initialisation.
It then calls for this and subsequent requests
the method void _jspService(HttpServletRe
quest, HttpServletResponse) to execute the
generated servlet. This method should never
be overridden. When no longer needed,
the container calls void jspDestroy() which can
be overridden for custom
finalisation. Java Server Pages can contain, in
addition to html markup - Directives
for setting various options using lt_at_ ... gt
tags Declarations for defining
constants, variables and methods using lt! ...
gt Scriplets fragments of Java code
using lt ... gt tags Actions which can
be standard actions or custom actions.
Expressions which evaluated code and insert
result using lt gt
P. Martin 2001 JSP - 1
2
Directives
JSP directives define global values and apply to
the whole JSP page. They do not result in any
output to the client. Any number of each type of
directive can be defined usually at the top of
the JSP page except for includes. The
page directive - used to define attributes for
the JSP page such as - import - comma
separated list of classes or packages (as for
Java program) session either true or false
indicates if page participates in an http
session. isThreadSafe either true or false
similar to defining SingleThreadModel. errorPage
url of page to be called if an exception
occurs. isErrorPage true or false indicates
if this is an error page. etc. other less
important ones. The include directive -
allows the source of other pages to be included
at this point. This is textual insertion at
compile time. Only one attribute file path
name of file to be included relative to this
application (starts with a forward
slash. The taglib directive used to
define libraries of custom JSP tags.
P. Martin 2001 JSP - 2
3
Declarations Scriptlets
Declarations - Java constant, variable and
method declarations can be inserted into a JSP
page by enclosing them between lt! and gt
tags. Scriptlets - Fragments of Java code can be
inserted between lt and gt tags. Expressions
- Evaluated, converted to string and output,
between lt and gt Comments - Enclosed by lt--
and --gt visible only in the JSP page Enclosed
by lt!- - and - - gt visible in generated servlet
code. Implicit objects - JSP provides a number
of variables representing important objects in
the web application as follows - request
The current HttpServletRequest object
response The current HttpServletResponse
object session The current
HttpSession object, if any application The
ServletContext object out An object
of the class JspWriter, similar to PrintWriter
config The ServletConfig object
page An instance of the generated
servlet from the page equivalent to this.
pageContext An instance of the class
PageContext giving access to page attributes.
P. Martin 2001 JSP - 3
4
Standard Actions - Beans
Java Beans are incorporated into JSP pages when
- They carry out significant amount of
work and involve substantial amounts of
Java code. They are likely to form
reusable components for other applications. They
are incorporated into JSP pages with the aid of
three standard actions -
ltjspuseBeangt to define the bean to be used and
how and instantiate the bean using the
supplied default constructor.
ltjspsetPropertygt to configure the bean by
setting it's properties using the beans setter
methods. ltjspgetPropertygt to retrieve
String output to be inserted into the JSP
page by calling the beans getter
methods. Beans are precompiled and packaged with
the application in the WAR file.
P. Martin 2001 JSP - 4
5
Standard Actions Beans (continued)
ltjspuseBeangt Attributes - id a
unique ID for the bean in the page(s)
scope scope of bean can be page, request,
session or application (defaults to page).
class the class name of the bean
beanName refers to the bean class or a
serialisation of it (e.g. a.b a/b.ser)
type the type of the scripting variable used by
the JSP could be the bean class, a super
class or an interface implemented by the bean
class (defaults to class attribute
value) ltjspsetPropertygt Attributes -
name ID of the bean, previously referenced in a
useBean tag. property name or a bean
property or in which case request
parameters are automatically matched to bean
properties. param optional used when
parameter name does not match bean property
name. value optional used to specify
value directly (not used with param) ltjspgetProp
ertygt Attributes - name ID of the
bean property name of property or
method with String getXXX() signature
P. Martin 2001 JSP - 5
6
Simple example of JSP with Bean - 1
The following example illustrates some simple use
of JSP and Java Beans. First, the
Welcome Bean - Note - The class
must be serialisable. There must be
a zero parameter constructor.
Setter and getter methods must
be supplied for editable
attributes. Additional getter
methods can provide generated
output.
package myBeans import java.io. public class
Welcome implements Serializable private
String name private String pastime
public void setName(String nme) name
nme //end setName public String
getName() return name //end
getName public void setPastime(String
hobby) pastime hobby //end
setPastime public String getPastime()
return pastime //end getPastime public
String getReverse() StringBuffer sb new
StringBuffer(name) return
sb.reverse().toString() //end getReverse
//end class Welcome
P. Martin 2001 JSP - 6
7
Simple example of JSP with Bean - 2
Next, An HTML form to capture client data
Resulting in the page display
JSP Demo Form
Please enter your name Please select a hobby
Surfing
Clear
Send
P. Martin 2001 JSP - 7
8
Simple example of JSP with Bean - 3
Then,a JSP page -
P. Martin 2001 JSP - 8
9
Simple example of JSP with Bean - 4
When run, the JSP page produces the output -
JSP Demo
Today is Fri Mar 08 142248 GMT-1000 2002 The
following code is repeated 3 times Your name is
Bill Your name is Bill Your name is Bill Your
hobby is Sailing Your name in reverse is
lliB Again in reverse is lliB The square of 3 is 9
The application directory structure is -
CATALINA_HOME\webapps\jspdemo\index.html
my.jsp WEB-INF\web.xml --empty
here classes\myBeans\Welcome.class
P. Martin 2001 JSP - 9
10
Simple example of JSP with Bean - 5
Finally, the generated servlet -
P. Martin 2001 JSP - 10
11
Other Standard Actions
ltjspparamgt Used to provide parameters for other
tags such as include, forward and
plugin. Attributes - name - the name of a
parameter. value - the string value of a
parameter. ltjspincludegt Includes another JSP
page or servlet at request processing time and
provides services similar to those of the
RequestDispatcher. Attributes - page - the
url of the included resource. ltjspforwardgt This
is similar in action. These two standard actions
parallel the operation of RequestDespatcher
include and forward actions in
Servlets. ltjspplugingt This provides a way of
plugging an Applet into a JSP page. Details of
this are provided separately. Many of the
attributes of this directive (e.g. code,
codebase, align, archive, height, width) are
the same as applet tags in HTML. One
important additional one is type ( either
JavaBean or Applet)
P. Martin 2001 JSP - 11
12
User-defined actions Custom Tags
JSP's allow users to define and use their own
tags by making use of a number of provided
Interfaces and Classes -
P. Martin 2001 JSP - 12
13
Custom Tag types
There are really two distinct types of Tag
- Tag classes which extend TagSupport
embracing the simple Tag interface and
the IterationTag interface. Tag classes which
extend BodyTagSupport which embrace all
three interfaces. Tags can be
nested within each other and can contain body
content as well as tag attributes. The
life-cycle of a tag derived from TagSupport
follows the following sequence - A call of
setPageContext() when first encountered in
page A call of setParent() to provide a tag with
reference to any enclosing tag Calls to
setValue() to pass attributes A call of
doStartTag() - when a start tag is
encountered Possible repeated calls of
doAfterBody() after processing tag body A call
of doEndTag() when body processing has
finished A call of release() when tag no longer
needed.
P. Martin 2001 JSP - 13
14
Tags extending TagSupport
These are either simple tags with no body
iteration, or iteration tags in which the body is
executed repeatedly . The methods that should be
defined are - doStartTag() - This is evaluated
when the tag is encountered and returns an int
with one of the values -
EVAL_BODY_INCLUDE if the body is to be
evaluated SKIP_BODY if the body content
is to be ignored. doAfterBody() - Only if
iteration is required. Evaluated when end
tag encountered and returns an int with one of
the values - EVAL_BODY_AGAIN if
iteration is to continue SKIP_BODY if
iteration is to terminate doEndTag() - This is
evaluated when the end tag is reached (after
any iterations have terminated) and returns an
int with value - EVAL_PAGE if rest of
JSP page is to be processed SKIP_PAGE
if rest of JSP page is to be ignored
P. Martin 2001 JSP - 14
15
Simple Tag using TagSupport - 1
First, the MyTag class definition -
P. Martin 2001 JSP - 15
16
Simple Tag using TagSupport - 2
and the MyIterTag class definition -
P. Martin 2001 JSP - 16
17
Simple Tag using TagSupport - 3
Then, the tag library descriptor hello.tld-
P. Martin 2001 JSP - 17
18
Simple Tag using TagSupport - 4
The jsp page my.jsp using the tags -
P. Martin 2001 JSP - 18
19
Simple Tag using TagSupport - 5
Finally, the web.xml file - and the
application directory structure - webaps\
my.jsp WEB-INF\ web.xml classes\
mytags\ MyTag.class
MyIterTag.class tlds\ hello.tld
P. Martin 2001 JSP - 19
20
Simple Tag using TagSupport - 6
And the output produced -
P. Martin 2001 JSP - 20
21
Tag Attributes -1
User-defined tags may have attributes just like
the standard action tags. These are handled in a
similar way to Bean attributes - The
TagHandler class defines property attributes
together with getter and setter methods as for
Bean properties. Attribute entries are added to
the Tag descriptor xml file. Attributes are
specified when the tags are called.
P. Martin 2001 JSP - 21
22
Tag Attributes -2
The TagHandler class which implements the Tag
could then be -
P. Martin 2001 JSP - 22
23
Adding scripting variables
Tags are able to define and add new variables to
the pageContext which can then be referenced in
the remainder of the page,for example, suppose a
Tag called getmax accesses a payroll database
and sets a variable maxSalary by finding the
maximum salary, the steps involved are -
Define the variable in the tag-descriptor
entry - Set the variable into the
pageContext within the Tag - Reference
variable in JSP page - One of the more
important additional attributes in the ltvariablegt
xml descriptor is scope which takes values -
NESTED variable available only within tag and
any nested tags
(default).
AT_BEGIN available from the tag start to end of
page. AT_END available from after the
end tag to end of page.
pageContext.setAttribute("maxSalary", max) //
max is a local variable in the TagHandler.
P. Martin 2001 JSP - 23
24
Body Tags Life Cycle
Body tags provide more comprehensive
functionality, allowing any body content to be
manipulated before being output. In effect, any
output produced within a body tag is buffered and
then output during execution of the doEndTag()
method. This allows the generated output to be
modified, filtered or even deleted if
necessary. The life cycle of a BodyTag involves
a number of calls from the JSP page as follows
- setPageContext is called to provide the tag
with the pageContext object. setParent() to tell
the tag its parent tag. tag attributes are
passed to the tag. doStartTag() is called when
beginning of tag is encountered setBodyContent()
is called to provide the tag with a means of
buffering output. doInitBody() is called to
initialise the BodyContent object. doAfterBody()
is called until iterations are complete. doEndTag
() is called after final iteration. release()
may be called to delete the tag instance.
P. Martin 2001 JSP - 24
25
Example use of BodyTag - 1
The following tag encrypts the body content using
a simple substitution cypher based on a key
passed to the page as a parameter. The Tag Class
is -
P. Martin 2001 JSP - 25
26
Example use of BodyTag - 2
The tag descriptor would then be -
And its use might be -
P. Martin 2001 JSP - 26
27
Some final points
The web container creates a new instance of a tag
for each use guaranteeing thread safe
code. The web container may also pool tag
instances and allocate them from a pool
for efficiency. Tag libraries can be 'jarred' up
for ease of distribution this is done by
including all tag classes within the jar together
with a tag descriptor called taglib.tld placed
in a directory META-INF. When accessed, the jar
(mylib.jar say) is placed in WEN-INF\lib
directory and in the JSP page referred to with
the directive - lt_at_ taglib uri
"/WEB-INF/lib/mylib.jar" prefix "something"
gt There are numerous tag libraries available
and more recently there has been much work done
by the Apache foundation and others to develop a
standard JSP tag library under the JSPTL
initiative. More information on this is available
from Apache-Tomcat.
P. Martin 2001 JSP - 27
Write a Comment
User Comments (0)
About PowerShow.com