Unit 6: JavaServer Pages - PowerPoint PPT Presentation

1 / 69
About This Presentation
Title:

Unit 6: JavaServer Pages

Description:

Unit 6: JavaServer Pages Building J2EE ... From the JSP Specification: ... applications containing dynamic Web content such as HTML, DHTML, XHTML and XML. ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 70
Provided by: jimdem
Category:
Tags: javaserver | dhtml | pages | unit

less

Transcript and Presenter's Notes

Title: Unit 6: JavaServer Pages


1
Unit 6 JavaServer Pages
Instructor Note To hide Instructor Notes, select
ViewComments
  • Building J2EE Applications in SilverStream

2
Session Objectives
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices

3
JSP Definition
  • From the JSP Specification
  • JavaServer Pages technology is the Java
    platform technology for building applications
    containing dynamic Web content such as HTML,
    DHTML, XHTML and XML. The JavaServer Pages
    technology enables the authoring of Web pages
    that create dynamic content easily but with
    maximum power and flexibility.
  • From the Suns J2EE Blueprint
  • JavaServer Pages (JSP) technology was designed
    to provide a declarative, presentation-centric
    method of developing servlets. Along with all the
    benefits servlets offer, JSP technology offers
    the ability to rapidly develop servlets where
    content and display logic are separated, and to
    reuse code through a component-based
    architecture.

4
JSP versus Servlets
  • Readability
  • Java embedded into HTML as opposed to servlets
    with content embedded into Java code
  • Ease of use
  • Code-free bean access
  • Simple include/forward
  • Flexibility
  • Custom tag libraries encapsulate complex
    functionality without Java coding

5
JSP versus ASP
6
JSP Architecture - Basic
JSP
Browser
JavaBean
Instructor Note Slide builds to show
process Build 1 Request is sent from the
browser to JSPBuild 2 The JSP could go directly
to data, but not a good ideaBuild 3 Normally,
JSP calls JavaBean componentBuild 4 JavaBean
component gathers data and returnsBuild 5 With
data from JavaBean the JSP formats and returns
the Response to the Browser
Servlet Container
Data
7
JSP Architecture MVC Pattern
Servlet (Controller)
Browser
(Model) JavaBean
JSP (View)
Instructor Note Slide builds to show
process Build 1 The Request is handled by a
controlling servletBuild 2 The Servlet
instantiates the JavaBeanBuild 3 The Servlet
redirects to the JSPBuild 4 The JSP calls the
JavaBean component to gathers data and perform
logicBuild 5 Using the return of the JavaBean,
the JSP formats and returns the Response to the
Browser
Servlet Container
Data
8
JSP Syntax
  • Comments client or server side
  • Directives messages to the JSP container
  • Declarations declare variables or methods
  • Expressions an expression to evaluate
  • Scriptlets code fragments

9
Comments
  • HTML comment viewable in pages source
  • Tag lt!-- --gt
  • Hidden comment viewable only in JSP code
  • Tag lt-- --gt

10
Directives
  • Messages to the JSP engine
  • Dont produce any output
  • Types
  • Page
  • Include
  • Tag libraries (more later)
  • Tag
  • lt_at_ gt

Instructor Note This slides introduces
Directives. The following slides give details
and examples on Page and Include Directives.
TagLibs are covered at the end of the unit.
11
Page Directives
  • Defines attributes for the entire page
  • Attributes include
  • Language
  • Superclass
  • Content Type (Each JSP can only return a single
    content type)
  • Example
  • lt_at_ page isThreadSafe"false" import"java.util.,
    java.net." errorPage"error.jsp" gt

12
Include Directives
  • Includes a static file
  • Could be a static HTML page or JSP
  • Parses the JSP elements in that file
  • Example
  • lt_at_ include file..\header.html"gt

13
Declarations
  • Declares variables or methods for use within the
    page
  • Be careful of putting too much code in the JSP.
    (More later)
  • Tag
  • lt! gt

14
Examples of Declarations
  • Variables
  • lt! boolean bDebug true gt
  • Dont forget to end variable declarations with a
    semicolon.
  • Methods
  • lt! public void debugPrint(String str)
  • if(bDebug) System.out.println(str)
  • gt

15
Expressions
  • Variables or method calls
  • Converted to a string
  • Included in the output page
  • Tag
  • lt gt
  • Example
  • lt EBCompany.getName() gt

16
Scriptlets
  • Java code fragments
  • Run when the request is processed by the JSP
  • Allows multiple lines of code
  • Be careful putting too much code in the JSP
  • Tag
  • lt gt

17
Example of Scriptlets
  • lt for (int i1 ilt4 i) gt
  • ltHltigtgt Hello World!lt/Hltigtgt
  • lt gt
  • Combines the use of expressions and scriptlets
  • Displays string Hello World! formatted with H1,
    H2, H3, and H4 tags
  • Instructor Note Added build to give you the
    opportunity to ask students
  • What two JSP concepts are combined here?
  • What does the Scriptlet generate?

18
Object Scope
  • Application
  • Objects accessible from pages within the same
    application
  • Session
  • Objects accessible from pages within the same
    session they were created
  • Request
  • Object accessible from pages processing the
    current request
  • Page
  • Objects accessible only within the page they were
    created

Most Visible
Least Visible
19
Implicit Objects
  • To simplify authoring, the JSP container provides
    these implicit objects, accessible throughout the
    page
  • request
  • response
  • session
  • out
  • application
  • page
  • pageContext
  • config
  • exception

20
Request and Response
  • request is a subclass of javax.servlet.ServletRequ
    est
  • Scope Request
  • getAttribute, getParameterNames,
    getParameterValues
  • response is a subclass of javax.servlet.ServletRes
    ponse
  • Scope Page
  • Not often used from JSPreferences generated when
    JSP is compiled to a servlet

21
Session and Out
  • session is an instance of javax.servlet.http.HttpS
    ession
  • Scope Session
  • getID, getValueNames, getValue, putValue
  • out is an instance of javax.servlet.jsp.JspWriter
  • Scope Page
  • clear, clearBuffer, flush, getBufferSize,
    getRemaining

22
Application and Page
  • application is an instance of javax.servlet.Servle
    tContext
  • Scope Application
  • getMimeType, getRealPath
  • page is an instance of java.lang.object
  • Scope Page
  • Synonym for the this operated
  • Not often used in JSP codegenerated when JSP is
    compiled to a servlet

23
PageContext and Config
  • pageContext is an instance of javax.servlet.jsp.Pa
    geContext
  • Scope Page
  • Encapsulates implementation dependent details,
    like JspWriters
  • findAttribute, getAttribute, getAttributesScope,
    getAttributesNameinScope
  • config is an instance of javax.servlet.servletConf
    ig
  • Scope Page
  • getInitParameter, getInitParameterName

24
Exception
  • exception is a subclass of java.lang.Throwable
  • Scope Page
  • The uncaught object that resulted in the error
    page being invoked
  • getMessage, getLocalizedMessage, printStackTrace
  • More on error handling later

25
Creating a JSP
  • Create the static HTML content of the page
  • Add JSP tags, as described previously
  • Create a WAR containing the JSP and any other
    necessary files
  • Deploy WAR file to J2EE server

26
Creating a JSP
Instructor Note Create a small Hello World JSP
from scratch, deploy to SilverStream and run in
the browser.
  • Demo

27
Exercise 6-1 Customer JSP
Instructor Note All the logic in this lab will
be placed in the JSP, itself. Future labs will
move it out. A good review of the lab is to
compare the previous lab, the servlet with this
JSP. Not much difference!! The question is,
How do we make the JSP lighter?? Move some
of the logic outas well talk about in the next
section
28
Debugging JSPs
  • Comments
  • Java comments lt// or / Java comment / gt
  • JSP comments similar to Java comments
  • HTML comments lt!-- ID ltrs.getString(ID)gt
    --gt
  • Output
  • out.println( ) send the msg to the page
  • System.out.println( ) send the msg to the
    console
  • Debug object
  • Better, more consistent control of the output
  • Tight coupling with all the pages that use it

Instructor Note This slide can be done as a
wrap-up to the lab or as a break during the lab.
The idea is to let students feel a little pain
with this first lab. Then, they will be much
more interested in hearing about debugging
techniques. Ask students the pros and cons of
each approach.
29
Session Objectives
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices

30
Using JavaBean Components
  • As mentioned previously, dont put too many
    declarations or scriptlets in your JSP code
  • Logic is best placed in a more reusable
    component, such as a JavaBean
  • A JavaBean contains
  • Private variables, called properties
  • Get and set methods for those properties that
    include the property name in the method name
  • Allows JavaBean introspection by the JSP engine

31
Simple JavaBean Example
public class CustNameBean private String
firstName public String getFirstName( )
return firstName public void
setFirstName(String inName) firstName
inName
32
ltjspuseBeangt
  • This tag associates an instance of a Java object
    within a given scope to a given ID.
  • JSP engine determines if the association is to a
    new or existing instance of the object
  • Syntax
  • ltjspuseBean id"name" scope"pagerequestsession
    application"
  • classclassName /gt
  • Example
  • ltjspuseBean idconnection scope request
    classcom.sssw.demo.Connection /gt

Instructor Note Review ScopeWhich one is most
narrow?
33
ltjspgetPropertygt
  • Places the value of a bean property in the output
    stream
  • Converts value to a string using toString( )
  • Syntax
  • ltjspgetProperty namebeanID propertypropertyN
    ame /gt
  • Example
  • ltjspgetProperty nameconnection
    propertyuserID /gt

34
ltjspsetPropertygt
  • Sets the value of properties revealed through
    JavaBean introspection
  • Syntax
  • ltjspsetProperty namebeanName
    propertypropertyName paramparameterName
    valuepropertyValue /gt
  • Where beanName is the id from the jspuseBean
  • Example
  • ltjspsetProperty nameconnection
    propertydbName valueSilverBooks /gt

35
ltjspforwardgt
  • Allows runtime dispatch of the current request to
    a static resource
  • Terminates execution of the current page
  • Forward to another JSP or servlet in the same
    context
  • Syntax
  • ltjspforward pageURLSpec /gt
  • Example
  • lt String whereTo /common/ someVar gt
  • ltjspforward pagelt whereTo gt /gt

36
ltjspincludegt
  • Provides for the inclusion of static and dynamic
    resources in the same context of the current page
  • Syntax
  • ltjspinclude pageURLSpec/gt
  • Or
  • ltjspinclude pageURLSpec flushtruegt
  • ltjspparam /gt
  • lt/jspincludegt
  • Example
  • ltjspinclude page/common/footer.html/gt

37
Summary of Include Mechanisms
38
Exception Handling
  • Regular JSPs use a page directive to specify the
    error page
  • lt_at_ page errorPageerrorPage.jsp gt
  • This causes any uncaught exceptions to be
    forwarded to the specified page
  • The error page flags itself to the JSP engine
    using the page directive
  • lt_at_ page isErrorPagetrue gt

39
Exercise 6-2 JavaBeanComponents and Exception
Handling
Instructor Notes Use this slide to highlight
that the output to the browser will be the same
as the previous lab. The change is improving the
architecture of the JSP.
40
Session Objectives
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices

41
HTML Forms Processing
  • Special design pattern used for processing form
    data
  • Pattern requires names of form input elements
    match bean property names
  • This allows you to assign all incoming values to
    the bean properties with a single statement
  • ltjspsetProperty nameconnection property /gt

42
HTML Form Processing Steps
  • Create an HTML Form, giving each element a name,
    as a JSP
  • Write the bean, defining properties, get, and set
    methods that correspond to the form elements
  • Add the ltjspuseBeangt tag to the JSP
  • Add the single ltjspsetPropertygt tag to set
    properties in the bean from the JSP
  • Add other processing, as needed

43
Exercise 6-3 Forms Processing
44
Session Objectives
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices

45
Tag Libraries
  • Another extension mechanism for JSPs
  • More flexible and extendible than JavaBean
    components
  • Better separation of interface and logic
  • Easier to implement MVC pattern
  • Specifies custom tags
  • Simplifies the JSP page
  • New in JSP 1.1

46
Tag Libraries versus JavaBeans
  • JavaBeans
  • Tags are fixed
  • Only properties are available
  • Constructors cant have arguments for
    initialization
  • Method calls require scriptlets
  • Tag libraries
  • Custom tags are much more flexible
  • Tags call methods, including constructors
  • Separation of concerns

47
Steps to Using Tag Libraries
  • Create the tag class (CustNameTag)
  • Extend TagSupport or BodyTagSupport
  • Specify methods (at least doStartTag( )
    anddoEndTag( ))
  • Create tag library descriptor
  • Put the tag classes into a JAR file
  • Add taglib location to web.xml
  • Add taglib directive to JSP
  • lt_at_ taglib uri/mytaglib prefixcust gt
  • Add tags to JSP
  • ltcustcustName/gt

Instructor Note This slide introduces the
steps. The detail follows.
48
JSP with TagLib Example
lt_at_ page errorPage"error.jsp" gt lttable
width"75" border"1" align"center"gt lttrgt
lttdgtltbgtFirst Namelt/bgtlt/tdgt lttdgtltbgtLast
Namelt/bgtlt/tdgt lttdgtltbgtEMaillt/bgtlt/tdgt
lt/trgt lt_at_ taglib uri/mytaglib" prefix"cust"
gt ltcustcustNamegt lttrgt lttdgtlt firstName
gtlt/tdgt lttdgtlt lastName gtlt/tdgt
lttdgtlt email gtlt/tdgt lt/trgt lt/custcustNam
egt lt/tablegt lt/bodygt lt/htmlgt
Instructor Note The Head is missing (for
space). Remind the students of our first lab and
all the Java code in the scriptlet. Then,
highlight how much simpler this JSP is. You
might also need to remind them of this as we get
into the complexities of the tag library classes
in the following slide. The goal is to hide the
complexity in Java and keep the JSPs simple.
49
TagSupport
  • Simple actions
  • Little or no content
  • Implements the Tag interface
  • doStartTag()
  • Fired when tag is encountered in the JSP
  • Returns SKIP_BODY or EVAL_BODY_INCLUDE
  • doEndTag()
  • Fired after start when end tag is encountered
  • Returns EVAL_PAGE or SKIP_PAGE

50
Definition of Body
  • The Body can include
  • Other actions
  • Scripting elements
  • Uninterpreted template text (as quoted from
    the JSP Specification, a.k.a Static HTML)

Instructor Note Check with the classyou may
want to back up and review the methods of the Tag
interface and their possible return codes.
51
BodyTagSupport
  • Actions with body
  • Implements BodyTag interface
  • BodyTag extends Tag (includes doStartTag and
    doEndTag)
  • doInitBody()
  • After doStartTag(), start the generation of the
    content
  • No return value (void)
  • doAfterBody()
  • Complete content and clean up
  • Returns EVAL_BODY_TAG or SKIP_BODY

52
doStartTag Example
public int doStartTag() throws
JspTagException try query() //query
the database next() //navigate to first row
set variables catch(Exception e) throw
new JspTagException(e.toString()) return
SKIP_BODY return EVAL_BODY_TAG
Instructor Note As an additional illustration,
the catch block might include a return of
SKIP_BODY to stop processing due to the exception.
53
doInitBody Example
public void doInitBody() //start the
content, set variables pageContext.setAttribute
("firstName", firstName) pageContext.setAttrib
ute("lastName", lastName) pageContext.setAttri
bute("email", email)
54
doAfterBody Example
public int doAfterBody() throws
JspTagException try if(next())
pageContext.setAttribute("firstName",
firstName) pageContext.setAttribute("lastName
", lastName) pageContext.setAttribute("email"
, email) return EVAL_BODY_TAG else
BodyContent body getBodyContent()
body.writeOut(getPreviousOut()) close()
//close statement connection return
SKIP_BODY catch (Exception e)
throw new JspTagException(e.toString())

Instructor Note Again, you might want to
highlight the two returns and note that the
SKIP_BODY indicates the end of processing for
this tag
55
doEndTag Example
public int doEndTag() throws JspTagException
//housekeeping return EVAL_PAGE //continue
processing JSP
56
TagExtraInfo
  • Describes scripting variables to the JSP
    container.
  • Allows variables to be used within a custom tag.
  • Points to server-side objects.
  • getVariableInfo() describes the scripting
    variables, including name, class, and scope.

57
TagExtraInfo Example
  • import javax.servlet.jsp.tagext.
  • public class CustNameTEI extends TagExtraInfo
  • public VariableInfo getVariableInfo(TagData
    data)
  • VariableInfo firstName new VariableInfo
  • ("firstName","String",true,VariableInfo.NESTED)
  • VariableInfo lastName new VariableInfo
  • ("lastName","String",true,VariableInfo.NESTED)
  • VariableInfo email new VariableInfo
  • ("email","String",true,VariableInfo.NESTED)
  • return new VariableInfo firstName,
    lastName, email

58
Tag Library Descriptor (TLD)
  • lt?xml version"1.0"?gt
  • lt!-- a tag library descriptor --gt
  • lttaglibgt
  • lttlibversiongt1.0lt/tlibversiongt
  • ltjspversiongt1.1lt/jspversiongt
  • ltshortnamegtcustomerlt/shortnamegt
  • lturigt/mytagliblt/urigt
  • ltinfogtA simple tag library for SilverStream's
    J2EE courselt/infogt
  • lttaggt
  • ltnamegtcustNamelt/namegt
  • lttagclassgttaglib.CustNameTaglt/tagclassgt
  • ltteiclassgttaglib.CustNameTeilt/teiclassgt
  • ltbodycontentgtJSPlt/bodycontentgt
  • ltinfogtOutputs first name, last name, and
    email addresslt/infogt
  • lt/taggt
  • lt/taglibgt

59
Including the Taglib in web.xml
lt!-- Customer Tag Library Descriptor --gt
lttaglibgt lttaglib-urigt/mytagliblt/taglib-urigt
lttaglib-locationgt/WEB-INF/taglib/customer.tldlt/t
aglib-locationgt lt/taglibgt
60
Steps to Using Tag Libraries
  • Create the tag class (CustNameTag)
  • Extend TagSupport or BodyTagSupport
  • Specify methods (at least doStartTag( )
    anddoEndTag( ))
  • Create tag library descriptor
  • Put the tag classes into a JAR file
  • Add taglib location to web.xml
  • Add taglib directive to JSP
  • lt_at_ taglib uri/mytaglib prefixcust gt
  • Add tags to JSP
  • ltcustcustName/gt

Instructor Note We repeated this Steps slide
as a review
61
Session Objectives
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices

62
MVC Model - Review
Servlet (Controller)
Browser
(Model) JavaBean
JSP (View)
Servlet Container
Data
63
Struts
  • Uses a tag library
  • Defines an MVC framework for
  • Separating flow of control from business logic
  • Automating form validation
  • Creating wizard-style forms spanning multiple
    pages
  • Creating internationalized applications
  • Struts is a part of the Jakarta/Apache project

Instructor Note Introduce the topic to pique
curiositynot enough to time to cover in detail.
64
Struts Implementation of MVC
Action.xml
2
3
Struts Framework
1
5
4
Browser
Action Form
6
(Model) JavaBean
7
JSP (View)
JSP (View)
JSP (View)
JSP (View)
8
65
Struts Demo
  • Demo
  • Run bookSearchForm.jsp to show the students how
    the search process looks.
  • Open bookSearchForm.jsp to show the source.
  • In the source, show the struts tags.
  • Highlight strutsmessage tags "filling" in the
    static text of the form with the appropriate
    language text from the ApplicationResource.propert
    ies files.
  • When the form submits, you are submitting to the
    action servlet "searchAction".
  • Open action.xml from the docroot/web-inf
    directory. Highlight the searchAction action.
    This specifies the action class as SearchAction
    and the two view JSPs, searchResults.jsp (for
    listing multiple books) and bookDetail.do (for a
    single book)
  • Inside the SearchAction class, a sql where clause
    is constructed and passed to the jdbcsource ejb.
    The result set (a java Collection) is returned.
    If the collection contains a single item, the
    process will forward to "Bookdetail" as defined
    in the action.xml. If the resultset has more than
    one item, the process is forwarded to "booklist"
    as defined in the action.xml
  • SilverBooks bookSearchForm.jsp

66
Servlets versus JSPs
  • JSPs
  • HTML with some embedded Java (but not too much!)
  • Better separation of concerns
  • Visual tools (evolving)
  • Single content type (per JSP)
  • Servlets
  • Java embedded with HTML content
  • More flexibility (including content type)
  • Better with binary data (files or dynamic images)
  • Better as mediator or controller (in MVC)

67
Exercise 6-4 Tag Librariesand Deployment
68
Review Questions
  • What are JSPs compiled to?
  • What are the benefits of JSPs or servlets?
  • What is the difference between JavaBean
    components and tag libraries?
  • Instructor Note
  • - Servlets
  • - Easier to read, separation of concerns
  • - Tag Libraries are more flexible, but more
    complex to implement

69
Unit Summary
  • JavaServer Pages Basics
  • JavaBean components
  • HTML forms processing
  • Tag libraries
  • Best practices
Write a Comment
User Comments (0)
About PowerShow.com