Web Component Development With Servlet and JSP ... - Project Kenai

drivercutInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 5 χρόνια)

328 εμφανίσεις

Web Component Development
With Servlet and
JSP™ Technologies
SL-314-EE5
Revision C.1
Copyright 2008 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.
Thisproductordocumentisprotectedbycopyrightanddistributedunderlicensesrestrictingitsuse,copying,distribution,anddecompilation.Nopartofthis
product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.
Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.
Sun,SunMicrosystems,theSunLogo,theDukelogo,Java,EJB,EnterpriseJavaBeans,JavaBeans,JavaNamingandDirectoryInterface,JavaServerPages,JavaServer,
JDBC,J2EE,J2SE,JSP,JVM,andSolarisaretrademarksorregisteredtrademarksofSunMicrosystems,Inc.intheU.S.andothercountries.
NetscapeandNetscapeNavigatoraretrademarksorregisteredtrademarkofNetscapeCommunicationsCorporation.
UNIXisaregisteredtrademarkintheUnitedStatesandothercountries,exclusivelylicensedthroughX/OpenCompany,Ltd.U.S. Government approval might be required when exporting the product.
RESTRICTEDRIGHTS:Use,duplication,ordisclosurebytheU.S.GovernmentissubjecttorestrictionsofFAR52.227-14(g)(2)(6/87)andFAR52.227-19(6/87),orDFAR252.227-7015
(b)(6/95) and DFAR 227.7202-3(a).
DOCUMENTATIONISPROVIDED“ASIS”ANDALLEXPRESSORIMPLIEDCONDITIONS,REPRESENTATIONS,ANDWARRANTIES,INCLUDINGANYIMPLIEDWARRANTY
OFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEORNON-INFRINGEMENT,AREDISCLAIMED,EXCEPTTOTHEEXTENTTHATSUCHDISCLAIMERSARE
HELD TO BE LEGALLY INVALID.
Export Commodity Classification Number (ECCN) Assigned: 23 March 2004
Copyright 2008 Sun Microsystems Inc. 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.
Ceproduitoudocumentestprotégéparuncopyrightetdistribuéavecdeslicencesquienrestreignentl’utilisation,lacopie,ladistribution,etladécompilation.
Aucunepartiedeceproduitoudocumentnepeutêtrereproduitesousaucuneforme,parquelquemoyenquecesoit,sansl’autorisationpréalableetécritedeSun
et de ses bailleurs de licence, s’il y en a.
Lelogicieldétenupardestiers,etquicomprendlatechnologierelativeauxpolicesdecaractères,estprotégéparuncopyrightetlicenciépardesfournisseursdeSun.
Sun,SunMicrosystems,lelogoSun,lelogoDuke,Java,EJB,EnterpriseJavaBeans,JavaBeans,JavaNamingandDirectoryInterface,JavaServerPages,JavaServer,
JDBC, J2EE, J2SE, JSP, JVM, et Solaris sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.
NetscapeestunemarquedeNetscapeCommunicationsCorporationauxEtats-Unisetdansd’autrespays.intheUnitedStatesandothercountries.
UNIXestunemarqueenregistreeauxEtats-Unisetdansd’autrespaysetlicenciéeexclusivementparX/OpenCompanyLtd.L’accord du gouvernement américain est requis avant l’exportation du produit.
LADOCUMENTATIONESTFOURNIE“ENL’ETAT”ETTOUTESAUTRESCONDITIONS,DECLARATIONSETGARANTIESEXPRESSESOUTACITESSONTFORMELLEMENT
EXCLUES,DANSLAMESUREAUTORISEEPARLALOIAPPLICABLE,YCOMPRISNOTAMMENTTOUTEGARANTIEIMPLICITERELATIVEALAQUALITEMARCHANDE,A
L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.
Web Component Development With Servlet and JSP™ Technologiesiv
2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Course Contents
About This Course....................................................................................Preface-xvii
Course Goals...........................................................................................................................Preface-xviii
Course Map................................................................................................................................Preface-xix
Topics Not Covered...................................................................................................................Preface-xx
How Prepared Are You?..........................................................................................................Preface-xxi
How to Learn From This Course...........................................................................................Preface-xxii
Introductions...........................................................................................................................Preface-xxiii
Icons..........................................................................................................................................Preface-xxiv
Typographical Conventions...................................................................................................Preface-xxv
Additional Conventions........................................................................................................Preface-xxvii
Introduction to Web Technologies.........................................................................1-1
Objectives.................................................................................................................................................1-2
Relevance..................................................................................................................................................1-3
Web Application Technologies.............................................................................................................1-4
Java™ EE 5...............................................................................................................................................1-5
Java EE 5 SDK..........................................................................................................................................1-7
Web Sites and Web Applications..........................................................................................................1-8
Execution of CGI Programs...................................................................................................................1-9
Execution of Java Servlets....................................................................................................................1-11
Using Separate Processes or Using Threads.....................................................................................1-13
Java Servlets...........................................................................................................................................1-14
JavaServer Pages™ Technology..........................................................................................................1-15
Concerns When Using Servlets and JSP™Technology...................................................................1-16
Web Application – Three-Tier Architecture......................................................................................1-18
Model-View-Controller (MVC) Architecture in a Web Application.............................................1-19
Web Component Development With Servlet and JSP™ Technologiesv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Model 2 Architecture............................................................................................................................1-20
Model 2 Frameworks............................................................................................................................1-21
Java EE Containers................................................................................................................................1-22
Java EE Architecture Example............................................................................................................1-23
Job Roles.................................................................................................................................................1-24
Web Application Migration.................................................................................................................1-25
Summary................................................................................................................................................1-26
Developing a View Component...............................................................................2-1
Objectives.................................................................................................................................................2-2
Relevance..................................................................................................................................................2-3
Types of View Components..................................................................................................................2-4
Soccer League Case Study.....................................................................................................................2-5
List Leagues Analysis Model................................................................................................................2-6
List Leagues Page Flow..........................................................................................................................2-7
Home Page HTML..................................................................................................................................2-8
List Leagues Page HTML.....................................................................................................................2-10
Hypertext Transfer Protocol................................................................................................................2-11
HTTP GET Method...............................................................................................................................2-12
HTTP Request........................................................................................................................................2-13
HTTP Request Headers........................................................................................................................2-14
HTTP Response.....................................................................................................................................2-15
HTTP Response Headers.....................................................................................................................2-16
Web Container Architecture................................................................................................................2-17
Request and Response Process...........................................................................................................2-18
Sequence Diagram of an HTTP GET Request...................................................................................2-22
List Leagues Architecture Model........................................................................................................2-23
TheListLeaguesServlet Code........................................................................................................2-24
TheListLeaguesServlet Code (Part 2)..........................................................................................2-25
TheListLeaguesServlet Code (Part 3)..........................................................................................2-26
Web Component Development With Servlet and JSP™ Technologiesvi
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheListLeaguesServlet Code (Part 4)..........................................................................................2-27
Soccer League Web Application Structure........................................................................................2-28
Configuring a Servlet Definition.........................................................................................................2-29
Configuring a Servlet Mapping..........................................................................................................2-30
Complete Deployment Descriptor.....................................................................................................2-31
Web Application Context Root...........................................................................................................2-33
Sun Java™ System Application Server Deployment.......................................................................2-34
WAR Files for Deployment.................................................................................................................2-35
Activating the Servlet in a Web Browser...........................................................................................2-36
Activating the ListLeagues View........................................................................................................2-37
Summary................................................................................................................................................2-38
Developing a Controller Component......................................................................3-1
Objectives.................................................................................................................................................3-2
Relevance..................................................................................................................................................3-3
Types of Controller Components.........................................................................................................3-4
Add a New League Analysis Model....................................................................................................3-5
Add League Boundary Components...................................................................................................3-6
Add a New League Page Flow..............................................................................................................3-7
Form Verification....................................................................................................................................3-9
Soccer League Web Structure..............................................................................................................3-10
Creating an HTML Form.....................................................................................................................3-12
Theform Tag.........................................................................................................................................3-13
Textfield Component............................................................................................................................3-14
Drop-Down List Component..............................................................................................................3-15
Submit Button........................................................................................................................................3-16
Complete Add a New League Form..................................................................................................3-17
Form Data in the HTTP Request.........................................................................................................3-18
HTTP GET Method Request................................................................................................................3-19
HTTP POST Method Request..............................................................................................................3-20
Web Component Development With Servlet and JSP™ Technologiesvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTP GET and POST Methods..........................................................................................................3-21
Developing a Controller Servlet.........................................................................................................3-22
Add League Analysis Model (Stage 1)...............................................................................................3-23
Servlet API to Retrieve Form Parameters..........................................................................................3-25
TheAddLeagueServlet Class Declaration.......................................................................................3-26
Retrieving Form Parameters and DataConversion.........................................................................3-27
Performing Form Validations.............................................................................................................3-28
Performing the Business Logic............................................................................................................3-29
Handling an Exception.........................................................................................................................3-30
Add League Analysis Model (Stage 2)...............................................................................................3-31
Add League Architecture Model (Stage2)........................................................................................3-32
Request Scope........................................................................................................................................3-33
Using a Request Dispatcher.................................................................................................................3-34
Developing theAddLeagueServlet Code........................................................................................3-35
TheSuccessServlet Code.................................................................................................................3-39
Summary................................................................................................................................................3-42
Developing Dynamic Forms....................................................................................4-1
Objectives.................................................................................................................................................4-2
Relevance..................................................................................................................................................4-3
Servlet Life Cycle Overview..................................................................................................................4-4
Servlet Class Loading.............................................................................................................................4-5
One Instance Per Servlet Definition.....................................................................................................4-6
Theinit Life Cycle Method.................................................................................................................4-7
Theservice Life Cycle Method...........................................................................................................4-8
Thedestroy Life Cycle Method...........................................................................................................4-9
Customizing the Add a New League Form......................................................................................4-10
Add League Architecture Model (Step 1)..........................................................................................4-11
TheAddLeagueFormServlet Code...................................................................................................4-12
Configuring Initialization Parameters...............................................................................................4-13
Web Component Development With Servlet and JSP™ Technologiesviii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheServletConfig API.....................................................................................................................4-14
TheAddLeagueFormServlet Code...................................................................................................4-15
Add League Analysis Model (Stage 2)...............................................................................................4-16
Error Handling Screen Shots...............................................................................................................4-17
Add League Architecture Model (Stage 2)........................................................................................4-18
Soccer League Web Application Structure........................................................................................4-19
TheAddLeagueServlet Code............................................................................................................4-21
TheAddLeagueFormServlet Code...................................................................................................4-22
Repopulating Web Forms....................................................................................................................4-25
Repopulating a Text Field....................................................................................................................4-26
Repopulating a Drop-Down List........................................................................................................4-27
Summary................................................................................................................................................4-28
Sharing Application Resources UsingtheServletContext.................................5-1
Objectives.................................................................................................................................................5-2
Relevance..................................................................................................................................................5-3
Soccer League Demonstration...............................................................................................................5-4
Servlet Context........................................................................................................................................5-5
TheServletContext API.....................................................................................................................5-6
Soccer League Architecture Model.......................................................................................................5-7
ModifiedAddLeagueServlet Code....................................................................................................5-8
ModifiedListLeaguesServlet Code................................................................................................5-9
ModifiedListLeaguesServlet Code (Part 2)................................................................................5-10
League List Initialization Example.....................................................................................................5-11
Web Application Life Cycle.................................................................................................................5-12
Soccer League Architecture Model (Revisited)................................................................................5-13
TheServletContextListener API..................................................................................................5-14
TheInitializeLeagues Code..........................................................................................................5-15
TheInitializeLeagues Code (Part 2)............................................................................................5-16
TheInitializeLeagues Code (Part 3)............................................................................................5-17
Web Component Development With Servlet and JSP™ Technologiesix
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Soccer League Deployment Descriptor.............................................................................................5-18
Soccer League Physical Hierarchy......................................................................................................5-19
Summary................................................................................................................................................5-20
Designing the Business Tier...................................................................................6-1
Objectives.................................................................................................................................................6-2
Relevance..................................................................................................................................................6-3
Describing the Analysis Model.............................................................................................................6-4
Registration Use Case Analysis Process..............................................................................................6-5
Detailed Analysis Model........................................................................................................................6-6
Another View: UML Sequence Diagram.............................................................................................6-7
Another View: UML Deployment Diagram.......................................................................................6-8
Domain Entities.......................................................................................................................................6-9
ThePlayer Code..................................................................................................................................6-10
ThePlayer Code (Part 2)....................................................................................................................6-11
ThePlayer Code (Part 3)....................................................................................................................6-12
Entity Service.........................................................................................................................................6-13
TheLeagueService Code...................................................................................................................6-14
TheLeagueService Code (Part 2).....................................................................................................6-15
TheLeagueService Code (Part 3).....................................................................................................6-16
TheLeagueService Code (Part 4).....................................................................................................6-17
Façade Service.......................................................................................................................................6-18
TheRegisterService Code..............................................................................................................6-19
TheRegisterService Code (Part 2)................................................................................................6-20
TheRegisterService Code (Part 3)................................................................................................6-21
Summary................................................................................................................................................6-22
Developing Web Applications UsingStruts..........................................................7-1
Objectives.................................................................................................................................................7-2
Relevance..................................................................................................................................................7-3
Web Component Development With Servlet and JSP™ Technologiesx
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Model-View-Controller Pattern............................................................................................................7-4
Struts MVC Framework.........................................................................................................................7-5
Front Controller Pattern.........................................................................................................................7-6
Struts MVC Framework.........................................................................................................................7-7
Struts Activity Diagram.........................................................................................................................7-8
StrutsAction Class.................................................................................................................................7-9
TheAddLeagueAction Code..............................................................................................................7-10
TheAddLeagueAction Code (Part 2)................................................................................................7-11
TheAddLeagueAction Code (Part 3)................................................................................................7-12
TheAddLeagueAction Code (Part 4)................................................................................................7-13
Configuring the Struts Action Mappings..........................................................................................7-14
Configuring the Infrastructure Controller........................................................................................7-15
Front Controller Servlet Mapping......................................................................................................7-16
Configuring Action Mappings............................................................................................................7-17
Action Mapping Object Representation............................................................................................7-18
Installing the Struts Library Files.......................................................................................................7-19
Summary................................................................................................................................................7-20
Developing Web Applications Using Session Management................................8-1
Objectives.................................................................................................................................................8-2
Relevance..................................................................................................................................................8-3
HTTP and Session Management...........................................................................................................8-4
Web Container Sessions.........................................................................................................................8-5
Designing Web Applications.................................................................................................................8-6
Registration Use Case Example............................................................................................................8-7
Registration Use Case Analysis Model................................................................................................8-8
Using Session Management in a Web Application............................................................................8-9
Session API.............................................................................................................................................8-10
Storing Session Attributes....................................................................................................................8-11
Accessing Session Attributes...............................................................................................................8-12
Web Component Development With Servlet and JSP™ Technologiesxi
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Destroying the Session.........................................................................................................................8-14
Using Cookies for Session Management...........................................................................................8-16
Cookie API.............................................................................................................................................8-17
Using Cookies Example.......................................................................................................................8-18
Performing Session Management Using Cookies............................................................................8-19
Using URL-Rewriting for Session Management..............................................................................8-22
URL-Rewriting Implications...............................................................................................................8-24
Summary................................................................................................................................................8-25
Using Filters in Web Applications..........................................................................9-1
Objectives.................................................................................................................................................9-2
Relevance..................................................................................................................................................9-3
Web Container Request Cycle...............................................................................................................9-4
Web Container Request Processing......................................................................................................9-5
Applying Filters to an Incoming Request............................................................................................9-6
Filters Applied to a Dispatch...............................................................................................................9-10
Filter API................................................................................................................................................9-11
ThePerformanceFilter Class..........................................................................................................9-12
Theinit Method..................................................................................................................................9-13
ThedoFilter Method.........................................................................................................................9-14
Thedestroy Method...........................................................................................................................9-16
Configuring the Filter...........................................................................................................................9-17
Summary................................................................................................................................................9-22
Integrating Web Applications With Databases....................................................10-1
Objectives...............................................................................................................................................10-2
Relevance................................................................................................................................................10-3
Designing a Web Application.............................................................................................................10-4
Domain Objects.....................................................................................................................................10-5
Database Tables.....................................................................................................................................10-6
Web Component Development With Servlet and JSP™ Technologiesxii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Data Access Object (DAO) Pattern.....................................................................................................10-8
DAO Pattern Advantages..................................................................................................................10-10
JDBC™ API..........................................................................................................................................10-11
Traditional Approaches to Database Connections.........................................................................10-12
Using a DataSource and JNDI API...................................................................................................10-14
ApplicationDataSource Use............................................................................................................10-15
Configuring a Sun Java Application Server DataSource and JNDI.............................................10-18
Sun Java Application ServerDataSource sun-web.xml Configuration..................................10-19
Summary..............................................................................................................................................10-20
Developing JSP™ Pages.......................................................................................11-1
Objectives...............................................................................................................................................11-2
Relevance................................................................................................................................................11-3
JavaServer Pages Technology..............................................................................................................11-4
Hello World Servlet..............................................................................................................................11-5
Thehello.jsp Page............................................................................................................................11-7
Steps of JSP Page Processing...............................................................................................................11-8
JSP Page Translation.............................................................................................................................11-9
JSP Page Compilation.........................................................................................................................11-10
JSP Page Class Loading......................................................................................................................11-11
JSP Page Servlet Instance...................................................................................................................11-12
JSP Page Initialization........................................................................................................................11-13
JSP Page Service..................................................................................................................................11-14
JSP Page Destroyed.............................................................................................................................11-15
Developing and Deploying JSP Pages.............................................................................................11-16
Writing JSP Scripting Elements.........................................................................................................11-17
Comments............................................................................................................................................11-18
Directive Tag........................................................................................................................................11-19
Declaration Tag...................................................................................................................................11-20
Scriptlet Tag.........................................................................................................................................11-21
Web Component Development With Servlet and JSP™ Technologiesxiii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Expression Tag....................................................................................................................................11-22
Implicit Variables................................................................................................................................11-23
Using thepage Directive...................................................................................................................11-25
Using Standard Tags..........................................................................................................................11-30
JavaBeans™ Components..................................................................................................................11-31
TheCustomerBean JavaBeans Component....................................................................................11-32
TheuseBean Tag.................................................................................................................................11-34
ThesetProperty Tag........................................................................................................................11-37
ThegetProperty Tag........................................................................................................................11-39
Using Expression Language (EL) Elements....................................................................................11-41
Bean Access Using EL........................................................................................................................11-42
EL Implicit Objects..............................................................................................................................11-43
Unified Expression Language...........................................................................................................11-46
Arithmetic Operators..........................................................................................................................11-47
Comparisons and Logical Operators...............................................................................................11-49
Configuring the JSP Environment....................................................................................................11-51
Summary..............................................................................................................................................11-53
Developing JSP Pages Using CustomTags........................................................12-1
Objectives...............................................................................................................................................12-2
Relevance................................................................................................................................................12-3
The Java EE Job Roles Involved in Web Application Development.............................................12-4
Contrasting Custom Tags and Scriptlet Code..................................................................................12-5
Developing JSP Pages Using Custom Tags.......................................................................................12-8
Custom Tag Library Overview...........................................................................................................12-9
Custom Tag Syntax Rules..................................................................................................................12-11
JSTL Sample Tags................................................................................................................................12-12
Theset Tag..........................................................................................................................................12-13
Theif Tag............................................................................................................................................12-15
TheforEach Tag.................................................................................................................................12-17
Web Component Development With Servlet and JSP™ Technologiesxiv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Theurl Tag..........................................................................................................................................12-20
Theout Tag..........................................................................................................................................12-22
Using a Custom Tag Library in JSP Pages.......................................................................................12-24
Using an Empty Custom Tag............................................................................................................12-25
Using a Conditional Custom Tag.....................................................................................................12-26
Using an Iterative Custom Tag.........................................................................................................12-27
Summary..............................................................................................................................................12-29
Developing Web Applications Using Struts Action Forms................................13-1
Objectives...............................................................................................................................................13-2
Relevance................................................................................................................................................13-3
Struts Application Components.........................................................................................................13-4
Struts Activity Diagram.......................................................................................................................13-5
Model Elements Review......................................................................................................................13-6
Control Elements Review....................................................................................................................13-7
View Elements Review.........................................................................................................................13-9
Developing anActionForm Class....................................................................................................13-10
The Add a New League Form...........................................................................................................13-11
TheAddLeagueForm Class.................................................................................................................13-12
TheAddLeagueForm Class (Part 2)...................................................................................................13-13
TheAddLeagueForm Class (Part 3)...................................................................................................13-14
TheAddLeagueForm Class (Part 4)...................................................................................................13-15
StrutsActionError Class..................................................................................................................13-16
How the Controller Uses the Form Bean.........................................................................................13-17
TheAddLeagueAction Class............................................................................................................13-18
Developing the JSP Code for a View Form.....................................................................................13-21
Strutshtml Tag Library Overview...................................................................................................13-22
Theadd_league.jsp Page...............................................................................................................13-23
Configuring the View Forms.............................................................................................................13-26
Configure the View Aspects of theActions..................................................................................13-27
Web Component Development With Servlet and JSP™ Technologiesxv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Summary..............................................................................................................................................13-28
Building Reusable Web Presentation Components............................................14-1
Objectives...............................................................................................................................................14-2
Relevance................................................................................................................................................14-3
Complex Page Layouts.........................................................................................................................14-4
Presentation Segment Overview........................................................................................................14-6
Organizing Presentation Segments....................................................................................................14-7
Including JSP Page Segments..............................................................................................................14-9
Using theinclude Directive.............................................................................................................14-10
Using thejsp:include Standard Action.......................................................................................14-11
Using thejsp:param Standard Action............................................................................................14-12
Developing Layouts Using Struts Tiles...........................................................................................14-15
ThelayoutPage.jsp Page...............................................................................................................14-16
ThelayoutPage.jsp Page (Part 2).................................................................................................14-17
ThelayoutPage.jsp Page (Part 3).................................................................................................14-18
ThelayoutPage.jsp Page (Part 4).................................................................................................14-19
Tiles Layout..........................................................................................................................................14-20
Content Body.......................................................................................................................................14-21
Summary..............................................................................................................................................14-22
Web Component Development With Servlet and JSP™ Technologies
Preface
About This Course
Preface
About This Course
Module 1
Introduction to
Web Application
Technologies
Preface
About This Course
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xviii of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
CourseGoals
•WriteservletsusingtheJava™programminglanguage
(Java servlets)
•Create robust web applications using Struts, session
management, filters, and database integration
•Write pages created with the JavaServer Pages™
technology (JSP™ pages)
•CreateeasytomaintainJSPpagesusingtheExpression
Language, JSP Standard Tag Library (JSTL), and the
Struts Tiles framework
•Create robust web applications that integrate Struts
and JSP pages
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xix of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
CourseMap
Java Servlet Application Strategies
Introduction to Web
Developing a
Application Technologies
Developing Dynamic
Sharing Application
Developing Web
Applications Using
Developing Web
Applications Using
Session Management
Using Filters in
Integrating Web
Web Applications
Applications With
Databases
JSP Application Strategies
Developing
JSP™ Pages
Developing
Developing Web
JSP Pages
Using Custom Tags
Applications Using
Struts Action Forms
Developing a
View Component
Controller Component
Forms
Struts
Resources Using the
Servlet Context
Building Reusable
Web Presentation
Components
Developing Web
Applications Using
JavaServer™ Faces
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xx of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TopicsNotCovered
•Java technology programming – Covered in SL-275:
The Java™ Programming Language
•Object-oriented design and analysis – Covered in
OO-226:Object-OrientedAnalysisandDesignUsingUML
•Java Platform, Enterprise Edition – Covered in WJT-
310:Java™ Platform, Enterprise Edition: Technology
Overview
•Enterprise JavaBeans™ technology – Covered in
SL-351:Enterprise JavaBeans™ Programming
•JavaServer™Facestechnology–CoveredinDTJ-3108:
Developing JavaServer™ Faces Components With AJAX
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxi of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HowPreparedAreYou?
To be sure you are prepared to take this course, can you
answer yes to the following questions?
•Can you create Java technology applications?
•Can you read and use a Java technology application
programming interface (API)?
•Canyouanalyzeanddesignasoftwaresystemusinga
modeling language such as Unified Modeling
Language (UML)?
•Can you create a simple web page using Hypertext
Markup Language (HTML)?
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxii of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HowtoLearnFromThisCourse
•Ask questions
•Participate in the discussions and exercises
•Read the code examples
•Use the on-line documentation for the Java Platform,
Standard Edition (Java SE platform), servlet, and JSP
APIs
•Read the servlet and JSP specifications
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxiii of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Introductions
•Name
•Company affiliation
•Title, function, and job responsibility
•Experience developing applications with the Java
programming language
•Experience with HTML and web development
•Experience with Java servlets or JSP pages
•Reasons for enrolling in this course
•Expectations for this course
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxiv of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Icons
Additional resources
Demonstration
Discussion
Note
Caution
1
2
3
?
!
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxv of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TypographicalConventions
•Courier is used for the names of commands, files,
directories, programming code, programming
constructs, and on-screen computer output.
•Courier bold is used for characters and numbers
that you type, and for each line of programming code
that is referenced in a textual description.
•Courieritalicisusedforvariablesandcommand-
lineplaceholdersthatarereplacedwitharealnameor
value.
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxvi of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TypographicalConventions(continued)
•Courieritalicboldisusedtorepresentvariables
whosevaluesaretobeenteredbythestudentaspartof
an activity.
•Palatino italic is used for book titles, new words or
terms, or words that are emphasized.
Web Component Development With Servlet and JSP™ TechnologiesPreface, slide xxvii of xxvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
AdditionalConventions
Java programming language examples use the following
additional conventions:
•Courier is used for the class names, methods, and
keywords.
•Methods are not followed by parentheses unless a
formal or actual parameter list is shown.
•Line breaks occur where there are separations,
conjunctions, or white space in the code.
•If a command on the Solaris™ Operating System
(Solaris OS) is different from the Microsoft Windows
platform, both commands are shown.
Web Component Development With Servlet and JSP™ Technologies
Module 1
Introduction to Web Technologies
Module 1
Introduction to
Web Technologies
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 2 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Objectives
•Describe web applications
•DescribeJavaPlatform,EnterpriseEdition5(JavaEE5)
•Describewebapplicationprogramexecutionmethods
and the advantages and disadvantages of each
•Describe Java servlet technology
•Describe JavaServer Pages technology
•Define three-tier architecture
•Define Model-View-Controller (MVC) architecture
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 3 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Relevance
•What web applications have you developed?
•Did your web technology allow you to achieve your
goals?
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 4 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebApplicationTechnologies
•HTML over HTTP
•Common Gateway Interface (CGI)
•Servlets
•JavaServer Pages (JSP) technology
•JSP Standard Tag Library (JSTL)
•XML
•Struts
•JavaServer Faces
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 5 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Java™EE5
•Java EE is the industry standard for developing
portable, robust, scalable and secure server-side Java
applications.JavaEEisbuiltonthesolidfoundationof
Java Platform, Standard Edition (Java SE).
•Java EE is a set of coordinated technologies which
includes the following web application technologies:
•Java Servlet 2.5 (Java Specification Requests [JSR]
154)
•JavaServer Pages 2.1 (JSR 245)
•JavaServer Pages Standard Tag Library (JSR 52)
•JavaServer Faces 1.2 (JSR 252)
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 6 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaEE5(continued)
ForacompletelistofJavatechnologies,goto:
http://java.sun.com/javaee/technologies/
http://java.sun.com/javase/technologies/
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 7 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaEE5SDK
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 8 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebSitesandWebApplications
•A web site is a collection ofstatic files, HTML pages,
graphics, and various other files.
•A web application is a web site withdynamic
functionality on the server.
•A web application run programs on the server, for
example:
•A browser makes a request, to the server, for an
HTML form.
•The server responds by sending the HTML form
back to the browser in an HTTP request stream.
•Next, the browser sends another request, with data
from the HTML form, to the server.
•Theserverpassestherequestanddatatoaprogram
that responds by sending data back to the browser.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 9 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ExecutionofCGIPrograms
One request to one CGI program:
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 10 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ExecutionofCGIPrograms(continued)
Many requests to one CGI program:
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 11 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ExecutionofJavaServlets
One request to one servlet program:
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 12 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ExecutionofJavaServlets(continued)
Many requests to one servlet program:
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 13 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
UsingSeparateProcessesorUsingThreads
•Advantagesofrunningprogramsinseparateprocesses
over threads:
•Programs can be written in a variety of languages
•Web designers can easily reference programs that
run in separate processes.
•Advantages of running servlet programs in threads
compared with other languages not in threads:
•The CPU requirements are lower.
•Java technologies separate processing code
(businesslogic)fromtheHTML(presentationlogic).
•The Java language is robust and object-oriented.
•The Java language is platform-independent.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 14 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaServlets
•AservletisaJavatechnologycomponentthatexecutes
on the server.
•Servlet programs perform the following:
•Process HTTP requests
•Generate dynamic HTTP responses
•A web container is a special Java Virtual Machine
(JVM™) tool interface that manages the servlets and a
thread pool.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 15 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaServerPages™Technology
•JSP pages are translated into Java servlet classes that
are compiled and execute as servlets in the web
container.
•JSPpagesshouldfocusonthepresentationlogic,noton
the business logic. This makes for a good design.
•InJSPpages,customtagsandJSPExpressionLanguage
provide for reusable code and separation of concerns.
•Java code can be embedded into JSP pages.
•In a Java technology web application, JSP pages are
often used in conjunction with servlets and business
objects in a Model-View-Controller pattern.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 16 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ConcernsWhenUsingServletsand
JSP™Technology
Advantages of JSP technology:
•Provides high performance and scalability because
threads are used
•Is built on Java technology, so it is platform-
independent.
•Can take advantage of the object-oriented language
and its APIs
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 17 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ConcernsWhenUsingServletsand
JSPTechnology(continued)
Disadvantages of JSP technology:
•If JSP pages are used in isolation, then the scripting
code that performs business and control logic can
become cumbersome in the JSP pages. JSP pages are
also difficult to debug.
•Thereisseparationofconcernsintobusinesslogicand
presentation logic.
•There are concurrency issues.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 18 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebApplication–Three-TierArchitecture
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 19 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Model-View-Controller(MVC)Architecturein
aWebApplication
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 20 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Model2Architecture
Deployment diagram of a web container using Model 2
architecture:
Client
«HTTP»
Database
Controller
Model
View
<%
%>
Web Container
Web Server
Web
Browser
HTTP response
HTTP request
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 21 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Model2Frameworks
•Frameworksarepartialimplementationsonwhichyou
can build your components.
•There are several Model 2 frameworks available:
•Struts from the Jakarta group
•JavaServer Faces technology from Sun
•Velocity from Apache
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 22 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaEEContainers
•Modular design allows for easier modification of the
business logic.
•Enterprise components can use container-provided
services such as presentation, security, transaction,
persistence, and life cycle management.
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 23 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JavaEEArchitectureExample
Internet Client
EJB Server
Web Server
«HTTP»
Database
Controller
Model
View
<%
%>
Web
Browser
GUI
Application
Web Container
EJB Container
Intranet Client
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 24 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
JobRoles
The modularity of Java EE architecture clearly distinguishes
several job roles:
•Web Designer – Creates View elements
•Web Component Developer – Creates Controller
elements
•Business Component Developer – Creates Model
elements
•Data Access Developer – Creates database access
elements
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 25 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebApplicationMigration
A matrix showing the relationship between an architecture’s
complexity and robustness, based on the technologies used:
Web Application
Robustness
Web Application Complexity
HTML pages
Basic JSP
pages and
servlets
JSP pages
with modular
components
JSP pages
with modular
components
and Enterprise
JavaBeans
￿
HTML pages
￿
JSP pages
￿
Servlets
￿
HTML pages
￿
JSP pages
￿
Servlets
￿
JavaBeans
TM
components
￿
Custom tags
￿
HTML pages
￿
JSP pages
￿
Servlets
￿
JavaBeans
components
￿
Custom tags
￿
Enterprise
JavaBeans
HTML pages
Web Component Development With Servlet and JSP™ TechnologiesModule 1, slide 26 of 26
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Summary
•CGI provided hooks for web servers to execute
application programs.
•Java servlets are similar to CGI, but they execute in a
JVM using threading.
•JSP pages are similar to servlets, but they are better
suited for generating HTML content.
•The Model 2 architecture uses servlets in conjunction
with JSP pages to build web applications.
•Well designed web applications using Model 2 can be
easilymigratedtomorecomplexJavaEEarchitectures.
Web Component Development With Servlet and JSP™ Technologies
Module 2
Developing a View Component
Module 2
Developing a
View Component
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 2 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Objectives
•Design a view component
•Describe the Hypertext Transfer Protocol
•Describe the web container behavior
•Develop a simple HTTP servlet
•Configure and deploy a servlet
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 3 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Relevance
•What is a view component?
•Whattypesofviewcomponentsareyoufamiliarwith?
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 4 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TypesofViewComponents
•Data presentation
•Data forms
•Navigational aids
•Informational screens or pop-ups
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 5 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
SoccerLeagueCaseStudy
Soccer League Web Application
List all available leagues
Add a new league
Register for a league
Player
League
Administrator
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 6 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ListLeaguesAnalysisModel
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 7 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ListLeaguesPageFlow
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 8 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HomePageHTML
1<html>
2
3<head>
4<title>Duke’s Soccer League: Home</title>
5</head>
6
7<body bgcolor=’white’>
8
9<!-- Page Heading -->
10<table border=’1’ cellpadding=’5’ cellspacing=’0’ width=’400’>
11<tr bgcolor=’#CCCCFF’ align=’center’ valign=’center’ height=’20’>
12 <td><h3>Duke’s Soccer League: Home</h3></td>
13</tr>
14</table>
15
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 9 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HomePageHTML(Part2)
16<p>
17This is the Home page for Duke’s Soccer League.
18</p>
19
20<h3>Players</h3>
21
22<ul>
23 <li><a href=’list_leagues.view’>List all leagues</a></li>
24 <li>Register for a league (TBA)</li>
25</ul>
26
27<h3>League Administrator</h3>
28
29<ul>
30 <li>Add a new league (TBA)</li>
31</ul>
32
33</body>
34
35</html>
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 10 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ListLeaguesPageHTML
9<!-- Page Heading -->
10<table border=’1’ cellpadding=’5’ cellspacing=’0’ width=’400’>
11<tr bgcolor=’#CCCCFF’ align=’center’ valign=’center’ height=’20’>
12 <td><h3>Duke’s Soccer League: List Leagues</h3></td>
13</tr>
14</table>
15
16<p>
17The set of soccer leagues are:
18</p>
19
20<ul>
21 <li>The Summer of Soccer Love 2004</li>
22 <li>Fall Soccer League (2003)</li>
23 <li>Fall Soccer League (2004)</li>
24 <li>Soccer League (Spring ‘03)</li>
25 <li>Summer Soccer Fest 2003</li>
26 <li>Soccer League (Spring ‘04)</li>
27</ul>
28
29</body>
30</html>
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 11 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HypertextTransferProtocol
The HTTP client sends a single request to the HTTP daemon
(httpd) and responds with the requested resource.
User WorkstationWeb Server
«HTTP»
HTTP response
HTTP request
<HTML>
</HTML>
Browserhttpd
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 12 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTPGETMethod
A web browser issues an HTTP GET request when:
•The user selects a link in the current HTML page
•TheuserentersaUniversalResourceLocator(URL)in
the Location field (NetscapeNavigator™) or the
Address field (Microsoft Internet Explorer)
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 13 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTPRequest
GET /soccer/list_leagues.view HTTP/1.0
Connection: Keep-Alive
User-Agent: Modzilla/4.76 [en] (x11; U, SunOS 5.8 sun4u)
Host: localhost:8088
Accept:image/gif,image/x-bitmap, image/jpg, image/pjpg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
HTTP methodRequested URLHTTP version
Request
line
Request
headers
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 14 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTPRequestHeaders
Headers are provided in the request by the client and can
modify how the request is processed on the server.
Example headers:
Header Use AcceptThe MIME types the client can receive
HostThe internet host and port number of the
resource being requested
RefererThe address from which the Request-Universal
Resource Identifier (URI) was obtained
User-AgentThe information about the client originating the
request
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 15 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTPResponse
HTTP/1.0 200 OK
Content-Type: text/html
Date: Tue, 10 Apr 2001 23:36:58 GMT
Server: Apache Tomcat/4.0-b1 (HTTP/1.1 Connector)
Connection: close
HTTP
version
Response
message
number
Text version of
the response
message
Status
line
Blank line
Message
body
Response
headers
<HTML>
<HEAD>
<TITLE>Hello Servlet</TITLE>
</HEAD>
<BODY BGCOLOR='white'>
<B>Hello World</B>
</BODY>
</HTML>
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 16 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
HTTPResponseHeaders
Headers are provided in the response by the server and can
modify how the response is processed on the client.
Example headers:
Header Use Content-TypeA MIME type (such astext/html) which
classifies the type of data in the response
Content-LengthThe length (in bytes) of the payload of the
response
ServerAn informational string about the server that
responded to this HTTP request
Cache-ControlA directive for the web browser (or proxies) to
indicate whether or not the content of the
response should be cached
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 17 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebContainerArchitecture
A web container can be used to process HTTP requests by
executing theservice method on anHttpServlet object.
User Workstation
Web Container
Web Server
«HTTP»
HTTP response
HTTP request
<HTML>
</HTML>
Database
Servlet
Browser
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 18 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
RequestandResponseProcess
Client
«TCP socket»
Web Container
Web Server
Web
Browser
The web browser initiates an HTTP request by opening
a TCP socket with the web server. The input stream of the
socket contains the HTTP request data. The output stream
of the socket contains the HTTP response data.
HTTP response
HTTP request
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 19 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
RequestandResponseProcess(Part2)
Client
«TCP socket»
«creates»
«creates»
Web Container
Web Server
Web
Browser
:HttpServlet
Request
:HttpServlet
Response
The Web container will create a request
object by parsing the HTTP request stream
data on the input stream of the socket.
The Web container will create a response
object that will generate the HTTP response
stream on the output stream of the socket.
HTTP response
HTTP request
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 20 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
RequestandResponseProcess(Part3)
Client
«TCP socket»
service(req,resp)
Servlet
Web Container
Web Server
Web
Browser
:HttpServlet
Request
:HttpServlet
Response
The web container will execute the
service method on the selected servlet.
The request and response objects are
passed as arguments to this method.
HTTP response
HTTP request
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 21 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
RequestandResponseProcess(Part4)
Client
«TCP socket»
service(req,resp)
Servlet
«TCP socket»
HTTP response
HTTP request
Web Container
Web Server
Web
Browser
:HttpServlet
Request
:HttpServlet
Response
:PrintWriter
The response object provides the servlet
with a PrintWriter object that allows the
servlet to generate the body of the response
using print or println methods.
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 22 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
SequenceDiagramofanHTTPGETRequest
User
HTTP GET request
request
:HttpServletRequest
response
:HttpServletResponse
«create»
«destroy»
«destroy»
service(request,response)
«create»
servlet
:HttpServlet
doGet
Web
Container
HTTP response
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 23 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ListLeaguesArchitectureModel
Web Container
Web Server
ListLeagues
Player
index.html
<HTML>
</HTML>
«Model»
«View»
League
http://localhost:8080/
soccer/index.html
http://localhost:8080/
soccer/list_leagues.view
2
1
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 24 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheListLeaguesServletCode
1package sl314.view;
2
3import javax.servlet.http.HttpServlet;
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6// Support classes
7import java.io.IOException;
8import java.io.PrintWriter;
9// Model classes
10import sl314.model.League;
11import java.util.List;
12import java.util.LinkedList;
13import java.util.Iterator;
14
15public class ListLeaguesServlet extends HttpServlet {
16
17 private List leagueList = null;
18
19 public void doGet(HttpServletRequest request,
20 HttpServletResponse response)
21 throws IOException {
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 25 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheListLeaguesServletCode(Part2)
15public class ListLeaguesServlet extends HttpServlet {
16
17 private List leagueList = null;
18
19 public void doGet(HttpServletRequest request,
20 HttpServletResponse response)
21 throws IOException {
22
23 // Create the set of leagues
24 leagueList = new LinkedList();
25 leagueList.add( new League(2003, “Spring”,
26 “Soccer League (Spring ‘03)”) );
27 leagueList.add( new League(2003, “Summer”,
28 “Summer Soccer Fest 2003”) );
29 leagueList.add( new League(2003, “Fall”,
30 “Fall Soccer League (2003)”) );
31 leagueList.add( new League(2004, “Spring”,
32 “Soccer League (Spring ‘04)”) );
33 leagueList.add( new League(2004, “Summer”,
34 “The Summer of Soccer Love 2004”) );
35 leagueList.add( new League(2004, “Fall”,
36 “Fall Soccer League (2004)”) );
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 26 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheListLeaguesServletCode(Part3)
37
38 // Set page title
39 String pageTitle = “Duke’s Soccer League: List Leagues”;
40
41 // Specify the content type is HTML
42 response.setContentType(“text/html”);
43 PrintWriter out = response.getWriter();
44
45 // Generate the HTML response
46 out.println(“<html>”);
47 out.println(“<head>”);
48 out.println(“ <title>” + pageTitle + “</title>”);
49 out.println(“</head>”);
50 out.println(“<body bgcolor=’white’>”);
51
52 // Generate page heading
53 out.println(“<!-- Page Heading -->”);
54 out.println(“<table border=’1’ cellpadding=’5’ cellspacing=’0’
width=’400’>”);
55 out.println(“<tr bgcolor=’#CCCCFF’ align=’center’ valign=’center’
height=’20’>”);
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 27 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
TheListLeaguesServletCode(Part4)
56 out.println(“ <td><h3>” + pageTitle + “</h3></td>”);
57 out.println(“</tr>”);
58 out.println(“</table>”);
59
60 // Generate main body
61 out.println(“<p>”);
62 out.println(“The set of soccer leagues are:”);
63 out.println(“</p>”);
64
65 out.println(“<ul>”);
66 Iterator items = leagueList.iterator();
67 while ( items.hasNext() ) {
68 League league = (League) items.next();
69 out.println(“ <li>” + league.getTitle() + “</li>”);
70 }
71 out.println(“</ul>”);
72
73 out.println(“</body>”);
74 out.println(“</html>”);
75 } // END of doGet method
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 28 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
SoccerLeagueWebApplicationStructure
The logical web application hierarchy:
The physical web application hierarchy:
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 29 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ConfiguringaServletDefinition
The web container will create one,
and only one, servlet object for each
definition in the deployment descriptor.
Web Container
Web Server
ListLeagues
web.xml
<XML>
</XML>
«View»
<servlet>
<servlet-name>ListLeagues</servlet-name>
<servlet-class>sl314.view.ListLeaguesServlet</servlet-class>
</servlet>
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 30 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ConfiguringaServletMapping
Web Container
Web Server
ListLeagues
web.xml
<XML>
</XML>
«View»
<servlet-mapping>
<servlet-name>ListLeagues</servlet-name>
<url-pattern>/list_leagues.view</url-pattern>
</servlet-mapping>
Player
index.html
<HTML>
</HTML>
http://localhost:8080/
soccer/index.html
http://localhost:8080/
soccer/list_leagues.view
The web container maps the URL of each request
to either a physical web resource (such as an HTML
page) or to a logical web resource (such as a servlet).
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 31 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
CompleteDeploymentDescriptor
0
1<?xml version=”1.0” encoding=”ISO-8859-1”?>
2
3<web-app
4 xmlns=”http://java.sun.com/xml/ns/j2ee”
5 xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
6 xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
7 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”
8 version=”2.4”>
9
10 <display-name>SL-314 WebApp Example</display-name>
11 <description>
12 This Web Application demonstrates a single View servlet.
13 </description>
14
15 <servlet>
16 <servlet-name>ListLeagues</servlet-name>
17 <servlet-class>sl314.view.ListLeaguesServlet</servlet-class>
18 </servlet>
19
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 32 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
CompleteDeploymentDescriptor
1.<?xml version=”1.0” encoding=”UTF-8”?>
2.<web-app version=”2.5” xmlns=”http://java.sun.com/xml/ns/
javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-
instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/
javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
3.
4. <servlet>
5. <servlet-name>ListLeagues</servlet-name>
6. <servlet-class>sl314.view.ListLeaguesServlet</servlet-
class>
7. </servlet>
8.
9. <servlet-mapping>
10. <servlet-name>ListLeagues</servlet-name>
11. <url-pattern>/list_leagues.view</url-pattern>
12. </servlet-mapping>
13.
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 33 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WebApplicationContextRoot
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 34 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
SunJava™SystemApplicationServer
Deployment
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 35 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
WARFilesforDeployment
Application Server deployment of a WAR file:
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 36 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ActivatingtheServletinaWebBrowser
Requestforhttp://localhost:8080/soccer/index.html
presents:
HTML:
Clicking on List performs a GET request for the URL:
http://localhost:8080/soccer/list_leagues.view
20<h3>Players</h3>
21
22<ul>
23 <li><a href=’list_leagues.view’>List all leagues</a></li>
24 <li>Register for a league (TBA)</li>
25</ul>
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 37 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
ActivatingtheListLeaguesView
Requestforthelist_league.viewissenttothecontainer:
This servlet generates this view:
Web Container
Web Server
ListLeagues
Player
«Model»
«View»
League
http://localhost:8080/
soccer/list_leagues.view
Web Component Development With Servlet and JSP™ TechnologiesModule 2, slide 38 of 38
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Summary
•Youcanuseaviewcomponenttodisplaydata,present
a form, present informational messages, and so on.
•The HTTP protocol provides a mechanism to request
static or dynamic views.
•The web container intercepts the HTTP request and
activates the necessary servlet.
•You can develop a servlet class that implements the
doGet method to process a request.
•Youcanaccessdatafromtherequeststreamusingthe
request object provided by the web container.
•You can generate a view by writing to the output
stream of the request object provided by the container.
Web Component Development With Servlet and JSP™ Technologies
Module 3
Developing a Controller Component
Module 1
Introduction to
Web Application
Technologies
Module 3
Developing a
Controller Component
Web Component Development With Servlet and JSP™ TechnologiesModule 3, slide 2 of 42
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Objectives
•Design a controller component
•Create an HTML form
•Describe how HTML form data is sent in the HTTP
request
•Develop a controller servlet
•Dispatch from a controller servlet to a view servlet