Download - WD51075INST
V5.2
cover
Front cover
Mastering Servlet and JSP Development with Rational Application Developer v7.5 (Course code RD810)
Instructor GuideERC 7.5
IBM certified course material
Instructor Guide
Trademarks
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.
Other company, product and service names may be trademarks or service marks of others.
CICS IMS RationalRedbooks WebSphere
March 2009 edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis without any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. While each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
© Copyright International Business Machines Corporation 2009. All rights reserved.This document may not be reproduced in whole or in part without the prior written permission of IBM.Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
Instructor GuideV5.2
TOC
ContentsTrademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Unit 1. Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Course Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8Course Objectives (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10Course Objectives (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12Agenda - Day 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14Agenda - Day 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16Agenda - Day 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18Agenda - Day 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20Agenda - Day 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Unit 2. Java EE Web Component Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2Web Application Evolution – Static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4Web Application Evolution – Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Web Application Evolution – Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8Web Application Evolution – JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10Web Application Evolution – Scalability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12The Model-View-Controller Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14MVC – Application to J2EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16MVC – Benefits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18J2EE Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20J2EE Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22J2EE Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24J2EE Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26J2EE Multitier Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28J2EE Benefits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-34
Unit 3. Servlet Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2What Is a Servlet? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4HTTP Flows Example - Forms / POST Request . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6HTTP Flows Example - HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8HTTP Protocol – Sample Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10HTTP Protocol – Sample Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents iii
Instructor Guide
Servlet Process Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-14Building a Simple Java Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-16A Simple Java Servlet Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-18Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-20Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-22
Unit 4. Supporting Perspectives for Developing Java EE Applications . . . . . . . . . .4-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2J2EE Application -> Modules -> Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4Application Developer Project Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7Building a Simple Enterprise Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9Creating an Enterprise Application Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-11Manage Project Facets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-13Add or Create Additional Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-15EAR Validator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-17Web Tooling - Web Perspective (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-19Web Tooling - Web Perspective (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-21Web Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-23Wizards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-25Dynamic Web Project Wizard (1 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-27Dynamic Web Project Wizard (2 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-29Dynamic Web Project Wizard (3 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-31Create Servlet Wizard (1 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-33Create Servlet Wizard (2 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-35Create Servlet Wizard (3 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-37Developing Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-39Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-41Run on Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-43Servers View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-46Test Environments and Server Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-48Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-50Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-52
Unit 5. Java EE Container Services Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-2J2EE Standard Services – Overview (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-4J2EE Standard Services – Overview (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-6J2SE Standard Services - JNDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-8J2SE Standard Services - JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-10J2EE Standard Services - Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-12J2EE Standard Services - JTA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-14J2EE Standard Services - Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-16J2EE Standard Services - JAXP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-18J2EE Standard Services - Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-20J2EE Standard Services - Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-22J2EE Standard Services - JAAS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-24J2EE Interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-26J2EE Platform Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-28
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
iv Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
J2EE Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-32Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-34Unit 6. Servlet API (Part I) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2Java Servlet Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4The Java Servlet API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7ServletConfig and Initialization Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9Servlet Definition in web.xml file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11Example Servlet with Init Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13HttpServlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15Requests and Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17HttpServletRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19Request Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-21Example HTML Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-23Reading a Post . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-25HttpServletResponse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-27Response Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-29Setting the Status Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-31Simple Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33Processing an HTTP Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35Processing Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-37Processing Input Data Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-41Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-43
Unit 7. Library Case Study Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2Library Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4Key Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6Patron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10Copies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12Loaned Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14Layers: Model, Data Store, Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18Use Case: Patron Login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20Use Case: List Checked Out Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-22Use Case: Renew Checked Out Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24Use Case: Register New Patron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26Use Case: Add Item to Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Unit 8. JavaServer Pages Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2Content within a Web Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4What Is JavaServer Pages? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents v
Instructor Guide
JSP Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-8JSP Syntax Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-10JSP or Servlet? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12JSP Benefits (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-14JSP Benefits (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16JSP Execution Model (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18JSP Execution Model (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-20The JSP Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-22Typical JSP Access Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-24Subsequent JSP Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-27Page Compilation in WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-29JSP Servlet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-31Scope Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-33Page Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-36Request Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-38Session Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-40Application Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-42JSP Positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-44Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-46Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-48
Unit 9. JavaServer Pages Specification and Syntax. . . . . . . . . . . . . . . . . . . . . . . . . .9-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-2JSP 2.0 Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-4JSP Syntax Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-6JSP Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-8The JSP Page Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-10JSP Page Directives - import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-12JSP Page Directives - session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-14JSP Page Directives - buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-16JSP Page Directives - autoFlush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-18JSP Page Directives - isErrorPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-20JSP Page Directives - errorPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-22JSP Page Directives - contentType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-24The <%@ include %> and <%@ taglib %> Directives . . . . . . . . . . . . . . . . . . . . . .9-26JSP Scripting (1 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-28JSP Scripting (2 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-30JSP Scripting (3 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-32JSP Scripting (4 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-34Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-36Scope Factors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-38Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-40The Include and Forward Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-42JSP Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-44Invoking a JSP by URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-46Calling a JSP Page from a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-48Invoking a Servlet from a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-50Invoking a JSP Page from Another JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-52
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
vi Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
Scripting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-54Scripting Example Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-56JSP Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-58JSP Document Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-60XML Tags (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-62XML Tags (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-64Document versus Page Syntax (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-66Document versus Page Syntax (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-68JSP Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-70Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-72Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-74Unit 10. Page Designer in Application Developer for JSP Development . . . . . . . 10-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4Page Designer Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6Page Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8HTML Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-12Rich HTML Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-14Editing HTML and JSP Tag Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-16JSP Expressions, Scriptlets, and Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18Custom Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20Web Project JSP Validator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-22Running JSP Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-24Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-26Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-28
Unit 11. Web Application Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2Debug Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4Enabling JSP Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6JSP Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-8Debug View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-10Variables View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-12Breakpoints View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-14Keep Generated Servlet Java Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-16View Generated Servlet code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-18Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-20Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Unit 12. Servlet API (Part II) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2Overview of Model-View-Controller (MVC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-4Model-View-Controller (MVC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6Controller Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-8Processing Request Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10Common Headers and HttpServletRequest Methods . . . . . . . . . . . . . . . . . . . . . 12-12
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents vii
Instructor Guide
Processing Request Headers (Example) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-14Setting the Response Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-16Content-Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-18Response Header (Example) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-20Response Redirection and Error Sending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-22Redirection and Send Error (Example) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-24Request Dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-26Request Dispatcher Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-28Sample Use of Request Dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-31Involving other Resources: Forwarding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-33Forward Method (Example) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-35Involving other Resources: Including . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-37Include Method (Example) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-39Sharing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-41Sharing Objects Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-43Servlet Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-45Web Containers and Servlet Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-47Servlet Objects (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-49Servlet Objects (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-51Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-53Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-55Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-57
Unit 13. Web Archive Deployment Descriptor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-2WAR File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-4Web Deployment Descriptor Editor (General) . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-6Web Deployment Descriptor Editor (Pages) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-8Web Deployment Descriptor Editor (Servlets) . . . . . . . . . . . . . . . . . . . . . . . . . . .13-11Web Deployment Descriptor Editor (Security) . . . . . . . . . . . . . . . . . . . . . . . . . . .13-14Web Deployment Descriptor Editor (Filters) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-17Web Deployment Descriptor (References) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-19Web Deployment Descriptor Editor (Extensions) . . . . . . . . . . . . . . . . . . . . . . . . .13-21Web Deployment Descriptor Editor (Source) . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-24Other Web Deployment Descriptor Editor Pages . . . . . . . . . . . . . . . . . . . . . . . . .13-26Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-28Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-30
Unit 14. Session State Storage Issues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-2The Session Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-4The Load Balancing Complication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-6The Load Balancing Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-8Session Strategies - Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-10Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-12Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-14
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
viii Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
Unit 15. Cookie API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4Cookie API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6Cookie Usage Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-8Proper Cookie Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-10Cookie Applicability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-12Client Data and Session Tracking with Cookies . . . . . . . . . . . . . . . . . . . . . . . . . 15-15Checking if Cookies Are Accepted on Browser . . . . . . . . . . . . . . . . . . . . . . . . . . 15-17Checking Cookie Configuration: Sample Code . . . . . . . . . . . . . . . . . . . . . . . . . . 15-19Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-21Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-23Unit 16. HttpSession: Management of Application Data. . . . . . . . . . . . . . . . . . . . . 16-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2Session Management (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4Session Management (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6Session Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-9HttpSession Data Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-11Sessions at Run Time - Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-13Sessions at Run Time - Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-15Sessions at Run Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-17Session Invalidation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-19Session Invalidation Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-22Session Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-24Bookstore Domain Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-26Book Choice Servlet (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-28Book Choice Servlet (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-30Credit Information Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-32Thread Safety . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-34HttpSession Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-36Session Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-38Servlet Objects (1 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-40Servlet Objects (2 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-42Servlet Objects (3 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-44Servlet Objects (4 of 4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-46WebSphere Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-48Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-50Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-52
Unit 17. URL Rewriting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2URL Rewriting (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-4URL Rewriting (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-6Servlet Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-8JSP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10URL Rewriting and Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-12Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-14
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents ix
Instructor Guide
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17-16
Unit 18. Best Practices for Session Management. . . . . . . . . . . . . . . . . . . . . . . . . . .18-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-3Session Strategies - Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-5Cookies for Session State (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-7Cookies for Session State (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-9Hidden Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-11Hidden Fields for Session State (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-13Hidden Fields for Session State (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-15Session Storage Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-17WebSphere Distributed Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-19WebSphere Application Server Session Affinity . . . . . . . . . . . . . . . . . . . . . . . . . .18-22Using HttpSession Objects Efficiently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-24WebSphere Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-27WebSphere Administration Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-29Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-31Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-33
Unit 19. JavaBeans and the Model-View-Controller Pattern . . . . . . . . . . . . . . . . . .19-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-3What Are JavaBeans? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-5Characteristics of a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-8Why Use Beans? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-10A Simple Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-13JavaBean Property Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-15Boolean Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-17JavaBean Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-19Model – View – Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-21MVC in J2EE (Server-side Programming) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-24Benefits of MVC Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-26Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-28Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-30
Unit 20. JavaServer Pages with JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-2Factoring Reusable Components and JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . .20-4JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-6Display Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-8JSP Pages and Results JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-10The <jsp:useBean /> Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-12Retrieving an Existing Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-15Bean Retrieval Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-17Creating a Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-19Instantiation from a Serialized Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-21The <jsp:getProperty /> Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-23Example: Using a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-25The <jsp:setProperty /> Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-27
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
x Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
JavaBeans in a JSP - Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-29JavaBeans in a JSP - Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-31JSP Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-33Bean Creation Roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-35Page Designer and JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-37jsp:useBean and jsp:setProperty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-39Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-41Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-43Unit 21. JSP Expression Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2JSP Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4Drawbacks of JSP Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-6What is JSP Expression Language? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-8EL Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-11Implicit Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-13Syntax Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-16Basic Syntax Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-19Named Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-21Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-23Functions Example - Add Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-25EL Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-27Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-29Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-31
Unit 22. JSP Custom Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2JSP Custom Tags Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4Why Use JSP Custom Tags? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-6Steps to Create and Use a Custom Tag Library . . . . . . . . . . . . . . . . . . . . . . . . . . 22-8Tag Usage Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-10JSP Page Without Custom Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-12Using Custom Tags with Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 22-14JSP Standard Tag Library (JSTL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-16Sample JSTL Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-18forEach Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-20Anatomy of a Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-22Tag Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-24Describing Tags to the JSP Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-26General Format of the TLD (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-28General Format of the TLD (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-30Location of TLD File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-32JSP Taglib Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-34Tag Handler Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-36Example Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-38Processing Tags with Attributes: How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . 22-40What Needs to Be Done? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-42The TransformTag Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-44
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents xi
Instructor Guide
The doTag() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-46The Taglib Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-48Using the <transform> Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-50Packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-52Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-54Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22-56
Unit 23. JSP Tag Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-2Overview of Tag Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-4Calling a Tag File from a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-6Body Content from Caller JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-8Parameters from Caller JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-10Fragments from Caller JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-12Tag Directive in Tag File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-14Attribute Directive in Tag File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-16Variable Directive in Tag File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-18Implicit Objects Available in a Tag File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-20Example of Calling a Tag File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-22Tag File with Body Content and a Fragment . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-24Tag File Packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-26Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-28Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-30
Unit 24. Servlet Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-2Introducing Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-4Typical Uses of Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-6Filter Processing Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-8Filter Chain Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-10doFilter() Nested Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-12Typical doFilter() Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-14Implementing a Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-16Application Developer Filter Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-18Creating a New Filter in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . .24-20The javax.servlet.Filter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-22The javax.servlet.FilterConfig Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-24The javax.servlet.FilterChain Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-26Describing the Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-28Example of a Filter Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-30Describing the Filter Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-32Examples of Filter Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-34Configuring Filters with Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . .24-36Configuring Filter Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-38Example of Configuring Filter Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-40Configuring Filters for Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-42Example of Configuring Filter Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-44Filters with RequestDispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24-46
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xii Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
Dispatcher Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-48Filter Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-50Logger Filter: Function Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-52Logger Filter: Deployment Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-54Logger Filter: init() and destroy() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-56Logger Filter: doFilter() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-58Logger Filter: How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-60FormChecker Filter: Function Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-62FormChecker Filter: Deployment Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-64FormChecker Filter: init() and destroy() Methods . . . . . . . . . . . . . . . . . . . . . . . . 24-66FormChecker: doFilter() Method (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-68FormChecker Filter: doFilter() Method (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . 24-70FormChecker Filter: How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-72Wrapping Request and Response Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-74Trailer Filter: Function Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-76Trailer Filter: Deployment Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-78Trailer Filter: init() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-80Trailer Filter: doFilter() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-82Custom Response: StringResponse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-84Trailer Filter: How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-86Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-88Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-90Unit 25. Servlet Listeners. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-3Basic Concepts of Servlet Event Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-5Examples of Servlet Listener Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-7How to Create a Servlet Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-9Selecting Servlet Listener Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-11Selecting Methods for ServletContext Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-13Selecting Methods for HttpSession Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-16Selecting Methods for ServletRequest Events . . . . . . . . . . . . . . . . . . . . . . . . . . 25-19Defining Listeners to the Web Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-22Sample Servlet Listener Application (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-24Sample Servlet Listener Application (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-27Creating New Servlet Listeners with Wizards(1 of 2) . . . . . . . . . . . . . . . . . . . . . 25-29Creating New Servlet Listeners with Wizards(2 of 2) . . . . . . . . . . . . . . . . . . . . . 25-31Maintaining the Listener Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-33Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-35Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-37
Unit 26. Best Practices for Server-Side Application Dev.. . . . . . . . . . . . . . . . . . . . 26-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-2The Layering Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-4Advantages of Layering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7Disadvantages of Layering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-9Two-Layer Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-11Problems with Two-layer Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-13
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents xiii
Instructor Guide
Three-layer Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-15Layering in J2EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-18Sample Layered Application (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-20Sample Layered Application (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-22Sample Layered Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-24Presentation Layer (Client) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-26Presentation Layer (Servlet) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-28Presentation Layer (Controller) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-30Presentation Layer (State Machine) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-32Business Layer (Action Processors) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-34Business Layer (Data Transfer Objects) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-36Business Layer (Session Facades) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-38Business Layer (Model Helpers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-41Data Layer (Mappers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-43Data Layer (Entity EJBs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-45Decoupling the Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-47Accessing the Data Layer Directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-49Physical Layering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-51Servlet Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-54JSP Design Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-56Other JSP Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-58Synchronizer Token: Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-60Synchronizer Token: Solution (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-62Synchronizer Token: Solution (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-64Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-66Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26-68
Unit 27. Java EE Packaging and Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-2J2EE Packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-4J2EE Packaging – Containment Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-6EJB Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-8Web Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-10Application Client Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-12Resource Adapter Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-14Enterprise Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-16Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-18Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27-20
Unit 28. Installing an Application in WebSphere Application Server V7.0 . . . . . . .28-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-2WebSphere Administration Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-4Administrative Console Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-6Administrative Console Navigation Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-8Applications: Console Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-10Applications: Installation (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-13Applications: Installation (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-15Applications: Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28-17
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xiv Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TOC
Servers: Configuration (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-19Servers: Configuration (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-21Resources: Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23Resources: JDBC DataSources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-25Resources: JMS Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-27Saving Master Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-29Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-31Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-33Unit 29. Web Application Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-1Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-2Role-based Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-4Define Security Roles for Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-6Constrain Access Based on Security Role . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-8Gather Roles in the Enterprise Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-10Web Container Client Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-12Configure Client Authentication Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-14Declarative and Programmatic Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-16Define Security Role References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-18Enterprise Application Security Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-20WebSphere Environment Security Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-22Security in WebSphere (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-24Security in WebSphere (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-26Manage Security in WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-28Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-30Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-32
Unit 30. Course Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-1What This Course Was About . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-4Other WebSphere Courses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-6Finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-8
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Contents xv
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xvi Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
TMK
TrademarksThe reader should recognize that the following terms, which appear in the content of this training document, are official trademarks of IBM or other companies:
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.
Other company, product and service names may be trademarks or service marks of others.
CICS® IMS™ Rational®Redbooks™ WebSphere®
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Trademarks xvii
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xviii Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
V5.2
cover
Front cover
Mastering Servlet and JSP Development with Rational Application Developer v7.5 (Course code RD810)
Instructor GuideERC 7.5
IBM certified course material
Instructor Guide
Prerequisites
To get the most out of this course offering, students must meet the following prerequisites. Students who do not meet these prerequisites may not be able to fully understand and utilize the materials presented in the course.
• Develop, test, and deploy Java applications (as covered in course JA341 Developing and Testing OO Applications with Java or equivalent.)
• Understand server-side Java applications (as covered in distance learning module VJ10A or equivalent).
Objectives
After completing this course, students should be able to:
• Describe the J2EE component model and its use in building server-side applications
• Use IBM WebSphere and IBM Rational tools (currently Rational Application Developer and WebSphere Application Server) for developing, debugging and testing server-side applications
• Develop and test servlets using IBM WebSphere and IBM Rational tools
• Develop and test JSP pages using IBM WebSphere and IBM Rational tools
• Develop and test JavaBeans using IBM WebSphere and IBM Rational tools
• Use JavaBeans, JSPs, and servlets in accordance with the Model/View/Controller (MVC) programming model.
• Develop, test and use JSP custom tags
• Describe deployment and run-time issues of J2EE-based applications including security, scaling, work load management in the context of WebSphere Application Server
March 2009 edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis without any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. While each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
© Copyright International Business Machines Corporation 2009. All rights reserved.This document may not be reproduced in whole or in part without the prior written permission of IBM.Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
Instructor Guide
• Assemble and perform integration testing of J2EE-based applications using WebSphere Application Server
• Identify the best practices needed to design and build Web applications (application frameworks and design patterns)
Curriculum relationship
Course WF351 or SW257 can be taken either before or after this course and is designed for Java developers developing EJBs and EJB clients. However, since Servlet technology comprises a less difficult topic, it is recommended that this course (RD810) be taken first.
Course WF381 or SW246 provides an administration course that discusses running WebSphere Application Server, and is targeted at server administrators.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxi Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxii Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor Guide
Agenda
Day 1
(00:30) Unit 1 - Welcome(00:45) Unit 2 - J2EE Web Component Introduction(00:45) Unit 3 - Servlet Overview(00:45) Unit 4 - Supporting Perspectives for Developing J2EE Applications(01:00) Exercise 1 - Simple Registration Servlet(00:20) Unit 5 - J2EE Container Services Overview(00:30) Unit 6 - Servlet API (Part I)(00:15) Unit 7 - Library Case Study Flow(00:15) Exercise 2 - Building the Library Database(01:00) Exercise 3 - Parameter Servlet
Day 2
(00:30) Unit 8 - JavaServer Pages Overview(00:30) Unit 9 - JavaServer Pages Specifications and Syntax(00:20) Unit 10 - Page Designer in Application Developer(00:10) Unit 11 - Web Application Debugging(01:10) Exercise 4 - Simple JSP Page(00:55) Unit 12 - Servlet API (Part II)(00:25) Unit 13 - Web Archive Deployment Descriptor(01:30) Exercise 5 - Calling JSP Pages from a Servlet
Day 3
(00:30) Unit 14 - Session State Storage Issues(00:10) Unit 15 - Cookie API(00:30) Unit 16 - HttpSession: Management of Application Data(00:10) Unit 17 - URL Rewriting(01:20) Exercise 6 - Session Management(00:25) Unit 18 - Best Practices for Session Management(00:25) Unit 19 - JavaBeans and the Model-View-Controller Patter(00:30) Exercise 7 - Create a JavaBean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxiii Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor Guide
Day 4
(00:20) Unit 20 - JavaServer Pages with JavaBeans(01:15) Exercise 8 - Combining Servlets, JSP Pages, and JavaBeans(00:45) Unit 21 - JSP Expression Language(01:00) Exercise 9 - Using JSP Expression Language(00:45) Unit 22 - JSP Custom Tags(00:15) Unit 23 - JSP Tag Files(00:45) Exercise 10- JSP Custom Tags(00:45) Unit 24 - Servlet Filtering(00:45) Exercise 11 - Servlet Filters
Day 5
(00:30) Unit 25 - Servlet Listeners(00:30) Unit 26 - Best Practices for Server-Side Application Development(00:15) Unit 28 - J2EE Packaging and Deployment(00:30) Unit 29 - Installing an Application in WebSphere Application Server V6.1(00:15) Unit 30 - Web Application Security(00:15) Unit 31 - Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxiv Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxv Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xxvi Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 1. WelcomeEstimated time
00:30
What this unit is about
This unit describes the audience, prerequisites, and overall objectives for RD810. The overall agenda for the course is also covered.
What you should be able to do
After completing this unit, you should be able to:
• Describe the target audience for RD810
• Explain the prerequisites for the course
• Describe the major objectives for the course
• Describe the agenda for this course offering
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-1
Instructor Guide
Figure 1-1. Introduction RD8107.5
Notes:
2
Introduction� RD810: Mastering Servlet & JSP Development with IBM
Rational Application Developer V7.5� Instructor:
� Please introduce yourself and provide your:�Name and organization�Object-oriented programming experience�Java™ knowledge�Java™Server Pages (JSP) and HTML knowledge�Knowledge of IBM® Rational® Application Developer and
IBM® WebSphere Studio and Rational)�WebSphere Application Server knowledge�Goals you hope to achieve by attending this course
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-3
Instructor Guide
Figure 1-2. Course Description RD8107.5
Notes:
3
Course description� This course introduces Java
developers to the development and testing of server-side applications based on the Java™ EE component model, using IBM® WebSphere® and IBM® Rational® tools
� The course covers development and testing of server-side applications that use servlets and JSP technology for the control and flow of e-business applications, and use Java™Beans technology JavaBeans to represent the business logic
� The course lasts 4.5 days and provides extensive hands-on labs throughout
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-5
Instructor Guide
Figure 1-3. Audience RD8107.5
Notes:
4
Audience� Audience:
�Java developers involved in building Web-based server-side application solutions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-7
Instructor Guide
Figure 1-4. Prerequisites RD8107.5
Notes:
5
Prerequisites� To get the most out of this course offering students must meet
the following prerequisites�Develop, test, and deploy Java applications�Understand the basics of server-side Java applications
� Students who do not meet these prerequisites may not be able to fully understand and utilize the materials presented in the course
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-9
Instructor Guide
Figure 1-5. Course Objectives (1 of 2) RD8107.5
Notes:
6
Course objectives (1 of 2)� After completing this course, you will be able to:
�Describe the Java EE component model and its use in building server-side applications
�Use WebSphere tools (Rational Application Developer and WebSphere Application Server) to build server-side applications
�Develop and test servlets using WebSphere tools�Develop and test JSP pages using WebSphere tools�Develop and test beans using WebSphere tools
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-11
Instructor Guide
Figure 1-6. Course Objectives (2 of 2) RD8107.5
Notes:
7
Course objectives (2 of 2)� After completing this course, you will also be able to:
�Use JavaBeans, JSP pages, and servlets in accordance with the Model-View-Controller (MVC) programming model
�Develop and test JSP custom tag libraries and servlet filters and listeners with Rational Application Developer
�Describe deployment and runtime issues of Java EE-based applications, including security, scaling, and workload management in the context of WebSphere Application Server
�Assemble and perform integration testing of Java EE based applications using the WebSphere Application Server
�Identify the best practices needed to design and build Web applications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-13
Instructor Guide
Figure 1-7. Agenda - Day 1 RD8107.5
Notes:
8
Agenda: Day 1� Module 1: Welcome and Introductions� Module 2: Java EE Web Component Introduction� Module 3: Servlet Overview� Module 4: Supporting Perspectives for Developing Java EE
Applications� Lab Exercise (Simple Registration Servlet)� Module 5: Java EE Container Services Overview� Module 6: Servlet API (Part I)� Java EE Container Services Overview� Library Case Study Flow� Lab Exercise (Building the Library Database� Lab Exercise (Parameter Servlet)
1
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-15
Instructor Guide
Figure 1-8. Agenda - Day 2 RD8107.5
Notes:
9
Agenda: Day 2� Module 8: JavaServer Pages Overview� Module 9: JavaServer Pages Specification and Syntax� Module 10: Page Designer in Application Developer� Module 11: Web Application Debugging� Lab Exercise (Simple JSP page)� Module 12: Servlet API Part II� Module 13: Web Archive Deployment Descriptor� Lab Exercise (Calling JSP Pages from a Servlet)
2
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-17
Instructor Guide
Figure 1-9. Agenda - Day 3 RD8107.5
Notes:
10
Agenda: Day 3� Module 14: Session State Storage Issues� Module 15: Cookie API� Module 16: HttpSession: Management of Application Data� Module 17: URL Rewriting� Lab Exercise (Session Management)� Module 18: Best Practices for Session Management� Module 19: JavaBeans and the Model-View-Controller Pattern� Lab Exercise (Create a JavaBean)
3
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-19
Instructor Guide
Figure 1-10. Agenda - Day 4 RD8107.5
Notes:
11
Agenda: Day 4� Module 20: JavaServer Pages with JavaBeans� Lab Exercise (Combining Servlets, JSP Pages, and
JavaBeans)� Module 21: JSP Expression Language� Lab Exercise (Using JSP Expression Language)� Module 22: JSP Custom Tags � Module 23: JSP Tag Files� Lab Exercise (JSP Custom Tags)� Module 24: Servlet Filtering� Lab Exercise (Servlet Filters)
4
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-21
Instructor Guide
Figure 1-11. Agenda - Day 5 RD8107.5
Notes:
12
Agenda: Day 5� Module 25: Servlet Listeners� Module 26: Best Practices for Server-Side Application
Development� Module 27: Java EE Packaging and Deployment� Module 28: Installing an Application in WebSphere Application
Server V7.0� Module 29: Web Application Security� Module 30: Course Summary
5
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-23
Instructor Guide
Figure 1-12. Unit summary RD8107.5
Notes:
13
Unit summary� You've seen the overall course objectives and a day-by-day
agenda. Let's get started!
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 1. Welcome 1-25
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 2. Java EE Web Component IntroductionEstimated time
00:20
What this unit is about
This section introduces the web component of the Java EE architecture.
What you should be able to do
After completing this unit, you should be able to:
• Understand the stages in the development of Web applications
• Describe the model-view-controller (MVC) design pattern
• Understand the importance of MVC in Java EE applications
• Describe the web component and container provided by a Java EE platform
• Describe the architecture of Java EE
How you will check your progress
Accountability:
• Checkpoint
References
http://java.sun.com/javaee/ Java EE at a Glance
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-1
Instructor Guide
Figure 2-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this unit, you will be able to:
� Differentiate the stages in the development of Web applications
� Describe the Model-View-Controller (MVC) design pattern� Relate the importance of MVC in Java EE applications� Explain the Web components and containers provided by a
Java EE platform� Discuss the Web architecture of Java EE
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-3
Instructor Guide
Figure 2-2. Web Application Evolution – Static RD8107.5
Notes:
The most basic type of Web site provides only static information in the form of Web pages – this is still very common. The role of the Web server here is simply to map the HTTP request onto a file system and deliver pages back to the client.
3
Web browser
Web server
File system
HTTP request
HTTP response
Client Network Server
Web application evolution: static
� Organizations want to make their information available to as many people in the world as possible
� This can be achieved by using the Web, delivering the information as static HTML pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-5
Instructor Guide
Figure 2-3. Web Application Evolution – Applets RD8107.5
Notes:
Static sites provide no way of customizing the information presented to the client. Java Applets can be used to provide some of this sort of customization by providing a more sophisticated user interface and possibly providing some interaction with back end systems. The server side of the system does not need to change in order for this to be accomplished, since the Web server is still just delivering files (now class files) to the client; the difference is the addition of a Java Virtual Machine in the browser.
4
Web Server
File System
HTTP Request
HTTP Response
Client Network Server
Web application evolution: applets
� With static HTML, users see passive page presentations that are always the same
� Presentation can be improved with Java applets or other client-side programs
Web Browser with JVM
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-7
Instructor Guide
Figure 2-4. Web Application Evolution – Servlets RD8107.5
Notes:
Applets have security constraints which restrict access to back-end systems. In order to introduce flexibility into the system the processing functionality is moved to the server. Now the Web server plug-in is used to decide whether a particular request is for a static resource (in which case the request is forwarded to the Web server) or a dynamic resource (in which case it is forwarded to the Web container for execution). It makes this decision based on a configuration file. The Web server plug-in is normally installed as part of the Web server, often automatically as part of the application server installation procedure.
5
Netw
ork
Web browser
Web server
File system
HTTP requestClient
Web server plug-in
Server
Web container
Web application evolution: servlets
� Applets cannot access data on back-end systems� A Web container can provide server-side components (such as
servlets), to generate dynamic content
Requests for dynamic
resources
Requests for static
resourcesHTTP response
Dynamicresponse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-9
Instructor Guide
Figure 2-5. Web Application Evolution – JSP Pages RD8107.5
Notes:
A combination of Servlets on their own introduces a problem – if a Servlet is responsible for returning all the content to a browser then the HTML (or other content) must be embedded in the Java code in some way. This is a problem in several ways: the fact that HTML is embedded in Java means it must be edited using a Java editor (so it is impossible to use a high-quality HTML editor providing preview facilities), the code must be produced by a Java developer (not a Web page designer, who should have more appropriate skills for presentation) and the tasks of controlling application flow and presentation may end up being mixed together (giving fewer opportunities for reuse, more difficult maintenance and fewer chances for parallel development). Using Java beans can help even further with this and this leads to the model-view-controller design pattern, which you will look at shortly.
The RequestDispatcher is a mechanism provided by the Web container for managing the process of passing a request/response pair on from one resource (such as a Servlet) to another (such as a JSP page).
6
JavaServer Page
JavaBean
RequestDispatcher
Request
Response
Web Containerservice(req,res)
methods()
methods()
forward(req,res)
service(req,res)
Web application evolution: JSP pages
� Servlets provide poor separation between business logic and presentation logic
� Use JSP pages and beans to improve separation
Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-11
Instructor Guide
Figure 2-6. Web Application Evolution – Scalability RD8107.5
Notes:
Scalability is a key requirement: deployers can set up an application with resources appropriate for an anticipated load, and if the load increases they can simply add more machines to increase the throughput. Scalability can be achieved in many ways: network routers, proxies, Web server plug-ins, Web containers, Java applications, and database servers.
7
Web application evolution: scalability
� Business requirements often involve high availability� Improved performance may be required as business grows� Both these requirements can be achieved through scaling
�Servers can provide redundancy in the system�By sharing the load between servers, performance can be
enhanced
Webbrowser
HTTPserver
Webcontainer
Webcontainer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-13
Instructor Guide
Figure 2-7. The Model-View-Controller Pattern RD8107.5
Notes:
An example of MVC in a Java EE context is provided on the next slide. Separating persistence from the model gives a further level of abstraction to the model, enhancing the benefits which will be considered shortly.
8
The Model-View-Controller pattern� Model-View-Controller (MVC) is a design pattern
�Very widely used and regarded as a core concept in Java EE development
�Various practical benefits (covered in more detail later)� Promotes code reuse� Reduces development time
�The model� Represents the underlying data and business logic in one place� Contains no information about the user interface
�The view� The user interface: things that the user can see and respond to� Represents a window into the model: there can be many of these
�The controller� Connects the model and the view� Is used to communicate between the model and view
� A fourth layer – persistence – is often added to the pattern
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-15
Instructor Guide
Figure 2-8. MVC – Application to J2EE RD8107.5
Notes:
This diagram shows how the main Java EE components provide an implementation framework for the MVC pattern. This idea is central to Java EE application development.
9
Java EE server
View
Controller
Database
Model
Persistence
MVC: application to Java EE
Webbrowser
Transferservlet Transfer
JavaBean
TransferResult
JavaBean
HTMLdoc
HTMLdoc
5
2
3
4
6
7
1
BalanceJSP
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-17
Instructor Guide
Figure 2-9. MVC – Benefits RD8107.5
Notes:
With MVC, developers can focus on which layer or technology they are most comfortable with.
10
MVC: benefits� Promotes code reuse
�The purpose of the model is to provide business logic and data access in one place
�You can reuse this logic in many applications at the same time, without the need for any extra coding
� Reduces development time�The model, view, and controller are developed in parallel
� Is more maintainable�You can change the view without affecting the model
� You can change the Web page view to display a chart instead of atable with no change to the model
�You can change the model without affecting the view� For example, the way in which an insurance premium is calculated
changes, but the interface to the business method remains the same
�You can move data without affecting the view or model� The layering concept allows for more flexibility
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-19
Instructor Guide
Figure 2-10. J2EE Introduction RD8107.5
Notes:
This definition of the Java EE platform comes from the Java EE specification.
11
Java EE introduction� The Java Platform, Enterprise Edition (Java EE) Specification
consists of:�The Java EE Platform
� A standard platform of containers, services, and communications�The Java EE Compatibility Test Suite
� To verify that a Java EE platform product complies with the standard� WebSphere Application Server V7.0 is Java EE 5 compatible
�The Java EE Reference Implementation� For prototyping Java EE applications, and for providing an operational
definition of the Java EE platform�The Java EE Blueprints
� Best practices for developing multi-tier, thin-client applications� Java EE is developed using the Java Community Process
�Collaboration between major enterprise software vendors�IBM actively contributes to the Java EE development
process
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-21
Instructor Guide
Figure 2-11. J2EE Components RD8107.5
Notes:
12
Java EE components� Java EE defines different types of components, which must be
supported by any Java EE product�This course will only cover Web components
� Servlets and JavaServer Pages� These provide the controller and view functionality in Java EE
� Component deployment can be managed using deployment descriptors (except applets)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-23
Instructor Guide
Figure 2-12. J2EE Containers RD8107.5
Notes:
13
Java EE containers� Java EE defines different types of containers.
� Containers manage the components that they contain.�This course will only cover Web component containers
� Provided by a Java EE application server
� Java EE components never interact with other Java EE components directly�They depend on the runtime support of containers�Interaction takes place using services provided by
containers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-25
Instructor Guide
Figure 2-13. J2EE Architecture RD8107.5
Notes:
These abbreviations are explained in the following slides. The required set of services for each type of container is specified in the Java EE specification and is covered in more detail later.
The diagram is taken directly from the Java EE 5.0 specification document found at http://jcp.org/aboutJava/communityprocess/final/jsr244/index.html.
14
Java EE architecture
RMI-IIOP
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-27
Instructor Guide
Figure 2-14. J2EE Multitier Model RD8107.5
Notes:
This diagram shows how the different containers and components allow the functionality of an application to be divided into tiers or layers. Software like WebSphere Application Server is often described as Application Integration Middleware, because it provides the range of services which allow the components in the middle of this diagram to integrate the front-end with the back end resources which are available within the enterprise.
15
EnterpriseInformationSystemsTier
Java EE multi-tier model
RelationalDatabases
Middle TierClient Tier
EnterpriseResourcePlanningSystems
LegacyapplicationsWeb
container(servlets,
JSP pages,HTML)
Webclient
Webclient
Firewall
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-29
Instructor Guide
Figure 2-15. J2EE Benefits RD8107.5
Notes:
16
Java EE benefits� Standards
�A wide range of standard services, components, clients, and tools are supported
�Applications are portable across Java EE platforms� Distribution
�Provides scalability for performance and availability� Common services
�Most commonly required services are provided by Java EE servers
� Component model�Good separation of development responsibilities�Good reuse of code and opportunities to share logic
between applications� Interoperability
�Integration with other systems using standard protocols
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-31
Instructor Guide
Figure 2-16. Checkpoint RD8107.5
Notes:
Write down your answers here:
17
Checkpoint1. What role does a servlet play in an MVC application? 2. What role does a JSP page play in an MVC application?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
18
Checkpoint solutions1. Servlets act as the controller in an MVC application
a) Do not generate HTMLb) Convert the incoming HTTP information to Java objectsc) Interact with the business modeld) Forward to JSPs to render the view
2. JSP act as the viewa) Do not contain business logicb) Simply display information
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-33
Instructor Guide
Figure 2-17. Unit summary RD8107.5
Notes:
19
Unit summaryHaving completed this unit, you are able to:
� Differentiate the stages in the development of Web applications
� Describe the model-view-controller (MVC) design pattern� Relate the importance of MVC in Java EE applications� Explain the Web components and containers provided by a
Java EE platform� Discuss the Web architecture of Java EE
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 2. Java EE Web Component Introduction 2-35
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 3. Servlet OverviewEstimated time
00:45
What this unit is about
This unit gives a brief introduction to servlets, discusses what servlets are, and how they can be used to generate dynamic content. The general flow of HTTP requests and responses is also discussed.
What you should be able to do
After completing this unit, you should be able to:
• Describe servlets
• Describe the servlet process flow
• Understand a simple Java servlet example
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-1
Instructor Guide
Figure 3-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this unit, you will be able to:
�Describe servlets�Apply the servlet process flow�Develop a simple Java servlet example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Discuss what is in this unit.
Details — This unit is a VERY brief introduction to servlets and gives the students just enough details to write a very simple servlet.
Additional information —
Transition statement — Look at what a servlet is.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-3
Instructor Guide
Figure 3-2. What Is a Servlet? RD8107.5
Notes:
According to the Java Servlet Specification (version 2.5): “A servlet is a Web component, managed by a container, that generates dynamic content. Servlets are small, platform-independent Java classes compiled to an architecture-neutral bytecode that can be loaded dynamically into and run by a Web server.” In short, a servlet is a piece of Java code that runs on the server on behalf of a request. This is similar to CGI. CGI (Common Gateway Interface) is the original mechanism to allow Web servers to run application code on behalf of a HTTP request.
Because a servlet is Java, it runs within a Java Virtual Machine supplied by the servlet runtime.
3
What is a servlet?� A servlet is a standard, server-side component of a Java EE
application that executes business logic on behalf of an HTTP request�It runs in the server tier (and not in the client)�It is a pure Java alternative to other technologies, such as
CGI scripts�It is managed by the Web container
request
response
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — For WebSphere, the Web container is WebSphere Application Server.
Transition statement — Next: HTML Flows Example - Forms / POST Request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-5
Instructor Guide
Figure 3-3. HTTP Flows Example - Forms / POST Request RD8107.5
Notes:
The form being processed here is HTML document musicSearch.html. This is a static HTML document. It could also have been produced as the output from a CGI script or a JSP.
4
The servlet generates an HTML response based on the input from the form. The Server returns the HTML document (response).Client or
browser
GET (request) HTML document musicSearch.html
Return (response) document
Submit form (POST action) (request)
Web Server / Application
Server
HTTP flows example: Forms / POST request� Invoke the MusicServlet Java servlet with data from a form
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: HTTP Flows Example - HTML
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-7
Instructor Guide
Figure 3-4. HTTP Flows Example - HTML RD8107.5
Notes:
This is an example of invoking MusicServlet from an HTML file using the POST method.
5
...
<form action="/Music/SearchServlet" method="POST">
<h3>Music Store Search</h3><br><strong>Type in the song title:</strong>
<input type="text" size="55" name="song_title"><br>
<strong>Type in the song artist:</strong>
<input type="text" size="55" name="song_artist"><br>
<input type="submit" value="Search"><br><strong>Display the first </strong>
<select name="limit_number" value=20 size="1">
<option>250</option><option>100</option><option>50</option><option>40</option>
<option>30</option><option selected>20</option><option>10</option></select>
<strong>documents found</strong></form>...
HTTP flows example: HTML
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: HTTP Protocol - Request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-9
Instructor Guide
Figure 3-5. HTTP Protocol – Sample Request RD8107.5
Notes:
HTTP is a simple, stateless protocol. When a client makes a request, an HTTP GET or POST request is sent to the server. The server processes the request and returns the results. At this point the transaction is complete.
Notice that the above example is doing a POST request for servlet /servlet/MusicServlet. Also notice the HTTP level (1.0 in this case) and other headers (Connection: User-Agent:, Host:, and so forth).
The posted data in this example is the text starting with song_title.
6
POST /Music/SearchServlet HTTP/1.1
Accept: */*
Referer: http://www.music.ibm.com/Music/musicSearch.html
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; …)
Host: localhost:9080
Content-Length: 50
Connection: Keep-Alive
Cache-Control: no-cache
song_title=Hello&song_artist=Jones&limit_number=20
HTTP protocol: sample request� Conversation between a browser and a server� Request phase
�Request (POST in this example)�Header values�A blank line�Posted data (if the request method is POST)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — This example of the request information is the actual data stream captured from a browser.
Transition statement — Next: HTTP Protocol - Response
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-11
Instructor Guide
Figure 3-6. HTTP Protocol – Sample Response RD8107.5
Notes:
The servlet processes the request and sends back a response to the client. Notice that in the response headers there is information about the protocol version (HTTP/1.1 in this case), the server, status information (OK - 200 in this case), content type (text/html), and additional response headers (including a cookie).
7
HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
Content-Language: en-US
Set-Cookie: JSESSIONID=000093gEM_2OosI_mR6GBkZLJy9:-1; Path=/
Transfer-Encoding: chunked
Date: Mon, 12 Mar 2007 18:32:27 GMT
Server: WebSphere Application Server/6.1
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Cache-Control: no-cache="set-cookie, set-cookie2“
<HTML>
<BODY>
<H1>Very simple dynamic document created on 01-Jun-2001</H1>
</BODY>
</HTML>
HTTP protocol: sample response� Response phase
�Status information (200 in this example)�Header values�A blank line�Output document (HTML)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Servlet Process Flow
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-13
Instructor Guide
Figure 3-7. Servlet Process Flow RD8107.5
Notes:
Servlets implement a common request-response paradigm for the handling of the message flow between the client and the server. This page shows a high-level client-to-servlet process flow.
javax.servlet.Servlet is an interface.
javax.servlet.GenericServlet implements the Servlet interface
The service() method is defined for all servlets.
8
URL request
response
Application serverWeb
serverBrowser(client)
Servlet instance
Servlet process flow� The client makes a request naming a servlet as part of the
URL.� The Web server forwards the request to a Web container,
which locates an instance of a servlet class.� The Web container calls the servlet's service method.� The servlet builds a response dynamically, and passes it to the
Web server. External resources may also be used.� The Web server sends the response back to the client.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Building a Simple Java Servlet for GET or POST Processing
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-15
Instructor Guide
Figure 3-8. Building a Simple Java Servlet RD8107.5
Notes:
A generic servlet should override its service() method. HTTP servlet usually does not override the service() method.
If you want your servlet to process both GET and POST requests, you can have the doGet() method call the doPost() method (or vice versa).
The doGet() and doPost() methods both return void and take two input parameters. The first parameter is of type HttpServletRequest, and the second parameter is of type HttpServletResponse. Both methods can throw the types ServletException and java.io.IOException.
9
Building a simple Java servlet� To create a servlet that responds to HTTP requests, you must:
�Create a class that extends javax.servlet.http.HttpServlet
�Override the doGet or doPost methods to process HTTP GET or POST requests� Process HttpServletRequest input values� Invoke the business process� Set the HttpServletResponse values� Output HTML to the output PrintWriter
� Servlets are inherently multithreaded
MyServletinstance
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: A Simple Java Servlet Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-17
Instructor Guide
Figure 3-9. A Simple Java Servlet Example RD8107.5
Notes:
The first thing your servlet needs to do is process any headers, cookies, input data or forms data in the HttpServeltRequest parameter. This servlet reads the User-Agent request header, which provides details about the user's browser.
Next your servlet should set any header values for the HttpServletResponse object. This servlet simply sets the status to SC_OK.
Finally your servlet builds the output document (an HTML document in this case).
10
package com.ibm.example.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
public class VerySimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String browser = request.getHeader("User-Agent");
response.setStatus(HttpServletResponse.SC_OK); // default
response.setContentType("text/html"); // default
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Simple servlet");
out.println("</TITLE></HEAD><BODY>");
out.println ("Browser details: " + browser);
out.println("</BODY></HTML>");
}
}
A simple Java servlet example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — This servlet is very simple, but does produce dynamic content, namely information about the browser client.
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-19
Instructor Guide
Figure 3-10. Checkpoint RD8107.5
Notes:
Write down your answers here:
11
Checkpoint1. What class should your Java servlet extend?2. What method needs to be overridden to process POST
requests?3. What method needs to be overridden to process GET
requests?4. What techniques could you use to process both GET and
POST requests?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint Solutions
12
Checkpoint solutions1. javax.servlet.http.HttpServlet
2. doPost()
3. doGet()
4. For most applications, there is no difference in the doGetor doPost processing. In that case, both methods could pass control to another method that invokes the common process.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-21
Instructor Guide
Figure 3-11. Unit Summary RD8107.5
Notes:
13
Unit summary� This unit covered the following topics:
� The basic steps needed to build a Java servlet for processing a request from a Web browser (client)
� The subclassing requirements of a Java servlet� The methods that are overridden to handle HTTP GET or
POST requests� It also presented a simple Java servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 3. Servlet Overview 3-23
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 4. Supporting Perspectives for Developing Java EE ApplicationsEstimated time
00:45
What this unit is about
This unit describes several perspectives and tools within IBM Rational Application Developer used to develop Java EE applications. In particular, this unit looks at the Java EE and Web perspectives.
What you should be able to do
After completing this unit, you should be able to:
• Create Enterprise Application projects in Application Developer
• Get around the various Application Developer Perspectives involved in developing and testing Web components
• Perform the basic steps necessary to build and test a simple servlet
How you will check your progress
Accountability:
• Checkpoint
References
http://www.ibm.com/software/awdtools/developer/application/support/index.html Rational Application Developer for WebSphere Software Support
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-1
Instructor Guide
Figure 4-1. Unit objectives RD8107.5
Notes:
There are two goals of this unit:
1. Use building and testing of a simple servlet as the basis for the type of tasks to be performed within Application Developer to develop and test a Web application.
2. Point out the main contributing perspectives involved in this development (other than the Java Perspective). These include:
Java EE Perspective
Web Perspective
Server Perspective
(optionally) Debug Perspective
2
Unit objectivesAfter completing this unit, you will be able to:
� Create enterprise application projects in Rational Application Developer
� Use the various Rational Application Developer perspectives involved in developing and testing Web components
� Perform the basic steps necessary to build and test a simple servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-3
Instructor Guide
Figure 4-2. J2EE Application -> Modules -> Components RD8107.5
Notes:
A Java EE application is packaged in an Enterprise Archive, a file with an .EAR extension. The application has a Deployment Descriptor (application.xml) allowing configuration to a specific container's environment when deployed. Java EE components are grouped in modules, and each module has its own deployment descriptor. The deployment descriptors are represented on this slide by square-cornered rectangles.
The Java EE specification allows default configurations for all applications to support deployment on Java EE server without any deployment descriptor.
EJB modules group related EJBs in a single module, and are packaged in Java Archive (JAR) files. Note that there is only one deployment descriptor for all of the EJBs in the module.
Web modules group Servlet class files, JSP pages, HTML files, and images. They are packaged in Web Application Archive (WAR) files.
Application client modules are packaged in Java Archive (JAR) files.
3
Java EE application > modules > components
WebDD
EJBModuleJAR file
WebModule
WAR file
ClientModuleJAR file
Java EEApplication
EAR fileInstalled
RARs
HTML,GIFs, etc.
JSPPages
ApplicationDD
Web Services
DD
ClientClasses
EJBs
EJBDD
Web Services
DD
ClientDD
Servlets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Resource Adapter files (part of the Java EE connector architecture) are packaged in Resource Adapter Archive (RAR files).Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-5
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Application Developer Project Mapping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-3. Application Developer Project Mapping RD8107.5
Notes:
Rational Application Developer organizes its project artifacts to mirror the Java EE .ear architecture.
There is a top-level project (Enterprise Application project) which represents the Java EE Application.
There are individual projects for each Java EE module. These are:
Web projects for Web modules
EJB projects for EJB modules
Client Application projects for Client Application modules
The projects must be related in that the module mapping defined in the application.xml file (Enterprise Application project) references each Java EE module. With this consistently defined (directly supported by the project creation wizards) the project validators keep the top-level .ear file (logical) synchronized with the individual module projects.
4
Rational Application Developer project mapping� Resources organized in a parallel structure to the Java EE
application� Enterprise application project corresponds to the Java EE
application itself �Manages the application.xml file�Holds the .war and .jar files that are associated with the
application� Projects for each Java EE component
�Web projects�EJB projects�Client application projects
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Building a Simple Enterprise Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-4. Building a Simple Enterprise Application RD8107.5
Notes:
Here are the major steps involved in building a simple enterprise application.
You need to build the enclosing projects -- through a single create project wizard.
Next build the assets, for example, servlets, JSPs, and HTML files.
Publish to a test server and run the application on the server (one button action).
You can test and debug directly in the test server.
5
Building a simple enterprise application� As a developer, you use several different perspectives when
you develop and test an enterprise application� Example: building a simple servlet� Steps include:
�Create an enterprise application project and associated module projects (Web module for servlet)
�Import and create module artifacts (create servlets, JSP pages, and Web pages)
�Add the enterprise application project to a server configuration (run on server)
�Launch the server in debug mode
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Creating an Enterprise Application Project
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-5. Creating an Enterprise Application Project RD8107.5
Notes:
Use the New Enterprise Application Project wizard to build enterprise application projects and initial Web, EJB, and application client projects.
By default, you can select different versions of IBM WebSphere Application Server and WebSphere Portal Server.
There are a number of different ways to access this wizard -- choosing the icon pictured will lead to a slightly different sequence of screens than choosing, for example, the New icon and proceeding from there.
Choosing a Configuration will determine which project facets are available. Project facets are seen on the next slide.
6
Creating an enterprise application project� Launch the New Enterprise Application Project wizard� Designate a name for the project� Choose the Target Runtime that defines the application server
type and version
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Manage Project Facets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-6. Manage Project Facets RD8107.5
Notes:
These facets will build an EAR file that can be deployed to an IBM WebSphere Application Server v7.0.
Show Runtimes displays a list of the available application servers that the project can run in.
7
Manage project facets� Project facets allow users to add and remove functionality from
a project� Select a facet to display the details and required facets� Select a facet and click the Runtimes tab to view runtime
composition
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Add or Create Additional Modules
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-7. Add or Create Additional Modules RD8107.5
Notes:
8
Add or create additional modules� Optionally, select existing module projects to add to the EAR
project, or create new ones
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: EAR Validator
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-8. EAR Validator RD8107.5
Notes:
In the Java EE space:
An Enterprise Application project has an EAR validator
A Web project has a WAR validator and a JSP validator (compilation)
An EJB project has both an EJB validator and a map validator
9
EAR validator� Rational Application Developer projects can have an
associated validator�Invoked on save, or explicitly from the pop-up menu
� The enterprise application project validator validates the following resources:�Deployment descriptor (application.xml)�All of the modules contained in the enterprise application�Security roles�EAR roles�EJB roles�EJB references�Resource references
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Tooling - Web Perspective (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-9. Web Tooling - Web Perspective (1 of 2) RD8107.5
Notes:
Much of the work (other than the development of Java code) with Web assets will be performed from the Web perspective.
The Web project manages the Web module deployment descriptor file (web.xml).
The main editor in this perspective is Page Designer, an HTML and JSP page editor.
10
Web tooling: Web perspective (1 of 2)� The Web perspective has tools for you to :
�Create a Web project�Create, validate, and edit XML, JSP, and HTML files�Edit and validate JavaScript files�Access custom JSP tag support (based on JSP 2.0)�Configure servlets and JSP pages in the web.xml Editor �Create servlets�Import and export WAR files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Tooling - Web Perspective (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-10. Web Tooling - Web Perspective (2 of 2) RD8107.5
Notes:
Management of Web asset consistency (hypertext links, and so on) are also managed from the view.
Specialized editors such as the CSS editor.
At project creation time you can specify inclusion of various taglibs. Alternatively, these can be added after the project is created through the project's Properties dialog.
Palette view provides you with the ability to drag and drop items onto an HTML or JSP editor session, such as bulleted list templates or skeleton scriptlets. These items are organized into drawers in the Palette view.
Support for building the project with the Struts framework or JavaServer Face is available. This includes a visual Web Diagram editor to design the application flow.
11
Web tooling: Web perspective (2 of 2)� Additional Web perspective tools:
�HTTP and FTP import�FTP export (simple resource copy) to a server�Graphic editing and animation �Cascading Style Sheet (CSS) editing support �Palette view�Struts support�Link viewing, parsing, and management�Integration with the WebSphere unit test environment�SIP Servlet API (Session Initiation Protocol) creation for
applications with multimedia conversations�Java™Server Faces (JSF) and AJAX (Asynchronous
Java™Script and XML) component layout�Portal application and portlets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-21
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Perspective
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-11. Web Perspective RD8107.5
Notes:
12
Web perspective� View and edit Web components: servlet, JSP tags, and others
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-23
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Wizards
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-12. Wizards RD8107.5
Notes:
13
Wizards� A series of wizards assist you in creating Web assets
Create a Web Page• HTML/XHTML• JSP• JSP Fragment
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Dynamic Web Project Wizard (1 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-13. Dynamic Web Project Wizard (1 of 3) RD8107.5
Notes:
Configurations group together a collection of facets. Facets add functionality to your projects. For example project builders, style sheets and included JAR files.
Note the Dynamic Web Project with XDoclet configuration choice. XDoclet allows you to embed tags directly in your source code to generate extra code.
For example you can use @web.servlet tag to indicate the deployment information for a servlet. The tags are then used to add deployment information to web.xml.
This course will use the standard builders from IBM Rational Application Developer v7.0 and not the XDoclet technology.
14
Dynamic Web Project wizard (1 of 3)� Specify
�Project name�Configuration�EAR membership
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Create Web Project Wizard (2 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-14. Dynamic Web Project Wizard (2 of 3) RD8107.5
Notes:
Project facets allow users to add and remove functionality from a project. In this case the project can be deployed as an EAR to an IBM WebSphere Application Server v6.1. You can select a facet to display a description. You can right-click a facet and Show Constraints to show the other facets that it depends on. You can also click on Show Runtimes to display the available runtimes.
Project facets can be added and removed using the Properties dialog of a project.
15
Dynamic Web Project wizard (2 of 3)�Choose project facets�Adds functionality to
a project�Manages project
builders�Configurations group facets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Create Web Project Wizard (3 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-15. Dynamic Web Project Wizard (3 of 3) RD8107.5
Notes:
16
Dynamic Web Project wizard (3 of 3)� Set the Context Root
�http://hostname:port/<contextRoot>/<resource>� Content directory
�Class files�Deployment
descriptor�JSP tags�Servlets�HTML�Other support files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Create Servlet Wizard (1 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-16. Create Servlet Wizard (1 of 3) RD8107.5
Notes:
One of the easiest ways to start building a simple servlet-based Web application is to launch the Create Servlet wizard.
To launch this from the Web perspective, right-click the project that will contain the servlet and click New ?Servlet from the context menu.
17
Create Servlet wizard (1 of 3)� Specify Class name and Java package� Select an existing servlet class
�To reuse it with different parameters or mappings
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Create Servlet Wizard (2 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-17. Create Servlet Wizard (2 of 3) RD8107.5
Notes:
18
Create Servlet wizard (2 of 3)� URL mappings that will invoke the servlet
�http://hostname:port/<contextRoot>/<URLMapping>� Name� Initialization Parameters in web.xml
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-35
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Create Servlet Wizard (3 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-18. Create Servlet Wizard (3 of 3) RD8107.5
Notes:
Once the servlet is created there will be a warning that it should define a serialVersionUID field because it implements java.io.Serializable. Use Quick Fix to Add generated serial version ID.
19
Create Servlet wizard (3 of 3)� Specify class modifiers, interfaces, and desired method stubs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-37
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Developing Servlets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-19. Developing Servlets RD8107.5
Notes:
The screen shot shows the web.xml (deployment descriptor) for the Web module. To get there from the Project Explorer, you can double-click either on the Deployment Descriptor icon or the web.xml file icon (under WebContent/WEB-INF) and then select the Servlets tab, or you can expand the Servlets entry under the Deployment Descriptor and double-click on the servlet itself. This entry for the MyServlet servlet was provided by the Create Servlet wizard.
A source (XML) view of the deployment descriptor is also available.
20
Developing servlets� Edit Java code using the Java Tooling � You can configure servlets within a Web module by editing the web.xml file (deployment descriptor)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-39
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Page Editor (Page Designer)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-20. Page Designer RD8107.5
Notes:
The main editor in the Web Perspective is Page Designer. It is a powerful page editor supporting development of HTML pages, JSPs, scripts and style sheets.
Page Designer supports other technologies that are not covered in this class. For example JavaServer Faces and AJAX.
21
Page designer� Design view, Source view, Split view, Preview� Content Assist available (Ctrl+Space)
ContentAssist
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-41
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Run on Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 4-21. Run on Server RD8107.5
Notes:
Once your Web components are built, you can run them in a test server. This requires configuring a test server, publishing the enterprise application (or Web module) to the corresponding server, and launching the application. These tasks can often be accomplished via a single operation. In the Web Perspective, locate the servlet, JSP, or HTML file you wish to test. Right-click on the resource and click Run As ? Run on Server. This will start the server, publish the project(s) and launch a Web browser with the appropriate URL.
If your server configuration requires data sources, classpath configuration, and so on, these configuration tasks need to have already been performed.
The default test server for Web projects, enterprise application projects, and EJB projects built with J2EE 1.4 is WebSphere Application Server V6.1. You can configure your Web project to use other servers as well.
Note the Run As ? Administrative Script menu entry. Application Developer can help you build administrative scripts to capture tasks. You can right-click on a Server and run WebSphere Administrative command assist to capture changes you make to the server
22
Run on server� To test a Web application, choose an element to invoke via
URL �For example, an HTML page, JSP, or servlet)
� Select Run As > Run on Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-43
Instructor Guide
via the administrative console. The server needs to be set up so that the command assist can see the changes. Refer to the tool help.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Server Perspective
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-45
Instructor Guide
Figure 4-22. Servers View RD8107.5
Notes:
23
Servers view� Allows creation, configuration, and control of servers� The list of applications deployed to the server appears in a tree
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — If your students are familiar with previous versions of Application Developer, you may want to tell them that Rational Application Developer v7.0 leverages Web Tools Platform (WTP) from Eclipse.
Server configuration occurs through the administrative consoles of the servers being configured.
Transition statement — Next: Test Environments and Server Configuration
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-47
Instructor Guide
Figure 4-23. Test Environments and Server Configuration RD8107.5
Notes:
The list of servers you can create, can be seen by right-clicking in the Servers view and selecting New.
You can see the context menu on the right by right-clicking on a server in the Servers view.
24
Test environments and server configuration� WebSphere Application
Server V7.0 is the default server for�Enterprise applications�EJB and Web projects
� The server administrative console is use to configure the server
� Projects can be run on different servers types and versions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-49
Instructor Guide
Figure 4-24. Checkpoint RD8107.5
Notes:
Write down your answers here:
25
Checkpoint1. What Java EE deployment descriptor configures a servlet?
How can you edit this file in Rational Application Developer?
2. Running an application in a test server is as easy as selecting what menu item?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
26
Checkpoint solutions1. The Web deployment descriptor resides in the web.xml
file. You can locate web.xml, or double-click the deployment descriptor entry (which is near the top of every Web project in the Project Explorer).
2. Run As > Run on Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-51
Instructor Guide
Figure 4-25. Unit summary RD8107.5
Notes:
27
Unit summary� Having completed this unit, you are able to:
�Create enterprise applications and Web projects in Rational Application Developer
�Create a servlet in the Web perspective�Perform the basic steps necessary to build and test a
simple servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 4. Supporting Perspectives for Developing Java EE Applications 4-53
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 5. Java EE Container Services OverviewEstimated time
00:20
What this unit is about
This unit describes the standard services provided by a Java EE container.
What you should be able to do
After completing this unit, you should be able to:
• Describe the services provided by a Java EE platform
• Describe the container services provided by Java EE
• Discuss Java EE interoperability
• List the Java EE platform roles
• Discuss the Java EE implementation
How you will check your progress
Accountability:
• Checkpoint
References
http://java.sun.com/javaee/technologies/javaee5.jsp Java Platform, Enterprise Edition 5 (Java EE 5)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-1
Instructor Guide
Figure 5-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this module, you will be able to:
�Describe the container services provided by Java EE�Explain Java EE interoperability�List the Java EE platform roles�Discuss the Java EE implementation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-3
Instructor Guide
Figure 5-2. J2EE Standard Services – Overview (1 of 2) RD8107.5
Notes:
These services (including JDBC and JNDI) are described in detail in the following pages.
3
Java EE standard services: overview (1 of 2)� Java EE provides standard services to facilitate interaction
with different technologies� This also insulates the developer from the actual
implementation of the service� Two services previously in Java EE are now in Java™ 2
Platform, Standard Edition ( J2SE 4): � JDBC (Java™ Database Connectivity), for relational
databases� JNDI (Java™ Naming and Directory Interface)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-5
Instructor Guide
Figure 5-3. J2EE Standard Services – Overview (2 of 2) RD8107.5
Notes:
JAX-RPC = Java API for XML Remote Procedure Call
SAAJ = SOAP with attachments API for Java
4
Java EE standard services: overview (2 of 2)� The standard services provided in Java EE include the
following:�HTTP ( Hypertext Transfer Protocol ) �Remote Method Invocation/Internet Inter-ORB Protocol (RMI-IIOP)�Java™ Interface Definition Language (Java IDL)�Java™ Transaction API (JTA)�Java™ Message Service (JMS)�Java™Mail�Java™Beans Activation Framework (JAF)�Java™ API for XML Parsing (JAXP)�Web Services, including:
� Java™ API for XML – Remote Procedure Call (JAX-RPC)� SOAP with attachments API for Java™ ( SAAJ)
�Java™ EE Connector Architecture (JCA)�Java™ Authentication and Authorization Service (JAAS)�Java™ Authorization Service Provider Contract for Containers
(JACC)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-7
Instructor Guide
Figure 5-4. J2SE Standard Services - JNDI RD8107.5
Notes:
Clients look up required EJBs or data sources using JNDI. The EJB specification recommends that EJBs should be stored in the java:comp/env/ejb context: each java component (java:comp) in the server has its own environment (env) which is maintained by the container and is configurable using the deployment descriptor – there is more information in the J2EE specification. A similar convention is used for JDBC data sources (java:comp/env/jdbc). A UserTransaction object can be obtained by looking up java:comp/UserTransaction.
JNDI is now considered part of J2SE (Core Java).
5
J2SE standard services: JNDI� Java Naming and Directory
Interface Standard Extension� JNDI provides directory and
naming functionality� The API is independent of the
directory implementation� JNDI enables applications to
discover and retrieve objects of any type
� JNDI is used to register EJBs and to access server-provided objects
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-9
Instructor Guide
Figure 5-5. J2SE Standard Services - JDBC RD8107.5
Notes:
JDBC is now considered part of J2SE (Core Java).
The Standard Extension also adds javax.sql.RowSet, which objects encapsulates sets of rows.
The JDBC Core API is in the java.sql package
The Standard Extension is in the javax.sql package
6
J2SE standard services: JDBC� JDBC is an API that provides vendor-
independent connectivity to a variety of relational databases
� JDBC functionality provides basic connectivity and core database-related classes
� The Standard Extension provides additional functionality�You can use the JNDI API to
manage data sources and connections
�Database vendors can provide connection pooling to enhance performance, particularly for server applications
�It offers support for distributed transactions, including support for the standard two-phase commit protocol used by JTA API
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-11
Instructor Guide
Figure 5-6. J2EE Standard Services - Communications RD8107.5
Notes:
CORBA is the “Common Object Request Broker Architecture”, a language-neutral architecture for distributed objects with which Java EE is compatible.
7
Java EE standard services: communications� Hypertext Transfer Protocol
�The HTTP client-side API is defined by the java.net package
�The server-side API is defined by the Servlet and JSP interfaces
�The client- and server-side APIs also support HTTP over secure sockets (HTTPS)
� RMI-IIOP�Allows RMI-style programming
independent of protocol�Implementation supports both the
RMI protocol (Java™ Remote Method Protocol, or JRMP) and CORBA IIOP
� Java IDL�Allows Java EE components to
invoke external CORBA objects using IIOP, which may be written in any language
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-13
Instructor Guide
Figure 5-7. J2EE Standard Services - JTA RD8107.5
Notes:
A UserTransaction can be looked up using JNDI. An application developer can use the UserTransaction object to control the transaction on the server, although developers should generally avoid controlling transactions in this way, preferring the automatic support provided by EJB containers instead.
8
Java EE standard services: JTA� Java Transaction API Standard
Extension�JTA specifies interfaces
between a transaction manager, and the parties involved in a distributed transaction system� The application, the resource
manager, and the application server
�JTA is implementation-neutral�For application developers,
the UserTransactioninterface is the key
�Application developers normally want to use container-managed transaction demarcation, instead of using JTA
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-15
Instructor Guide
Figure 5-8. J2EE Standard Services - Messaging RD8107.5
Notes:
9
Java EE standard services: messaging� Java Messaging Service Standard Extension
�The JMS API is a standard, vendor-neutral API used to access enterprise message systems
�Analogous to JDBC for databases�Allows for the delivery of asynchronous
messages in an application� The JMS client sending the message does
not have to wait until the message has been processed
� JavaMail Standard Extension and JAF�JavaMail is used to add e-mail capability
to applications�Includes classes that encapsulate
common mail functions and protocols�Uses the JavaBeans Activation
Framework to encapsulate message data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-17
Instructor Guide
Figure 5-9. J2EE Standard Services - JAXP RD8107.5
Notes:
10
Java EE standard service: JAXP� Java API for XML Parsing (JAXP)
�JAXP enables applications to parse and transform XML documents� Independent of XML processor
implementation�JAXP includes industry standard
components� DOM (Document Object Model)� SAX (Simple API for XML Processing)� XSLT (XML Style Language
Transformations)�JAXP adds additional functionality
beyond these standards� Java API for XML – Remote Procedure
Call (JAX-RPC)�Enables Java applications
incorporating XML-based RPC functionality according to the SOAP (Simple Object Access Protocol) 1.1 specification
� Java API for XML Registries (JAX-R)�APIs to access UDDI Registry
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-19
Instructor Guide
Figure 5-10. J2EE Standard Services - Web Services RD8107.5
Notes:
JAX-RPC and JAX-R are explained on the previous slide.
11
Java EE standard services: Web services� Web services have been part of Java EE since
Java™ 2 Platform, Enterprise Edition ( J2EE) version 1.4�JAX-RPC 1.1�JAX-R�Web Services for J2EE specification (JSR 109)
� Standard deployment model of a Web services application within a J2EE Application Server
�WS-I Basic Profile 1.0� Guidelines for interoperability in a heterogeneous
environment
�SAAJ 1.1: SOAP with attachments API for Java
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-21
Instructor Guide
Figure 5-11. J2EE Standard Services - Connectors RD8107.5
Notes:
12
Java EE standard services: connectors� Java EE Connector Architecture
(JCA)�Allows resource adapters that
support access to Enterprise Information Systems (EIS) that will be plugged into Java EE products
�Defines a connection management contract between a Java EE server and a resource adapter to allow connection pooling to EIS systems
�Defines a transaction management contract between the transaction manager and an EIS that supports transactional access� Also supports transactions that
are managed entirely by an EIS�Defines a security contract that
enables secure access to an EIS
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-23
Instructor Guide
Figure 5-12. J2EE Standard Services - JAAS RD8107.5
Notes:
13
Java EE standard services: JAAS� Java Authentication and Authorization Service
(JAAS)�JAAS can be used for two purposes:
� Authentication of users, to reliably and securely determine who is currently executing Java code, regardless of how the code is running
� Authorization of users to ensure that they have the permissions required to do the actions performed
�JAAS authentication is pluggable� Java applications using JAAS remain independent from
underlying authentication technologies
�JAAS authorization extends the existing Java security architecture� Access control can be based not just
on what code is running, but also on who is running it
�Java Authorization Service Provider Contract for Containers (JACC)� Allows custom authorization service providers to be
plugged into the Application Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-25
Instructor Guide
Figure 5-13. J2EE Interoperability RD8107.5
Notes:
14
Java EE interoperability� The Java EE platform includes interoperability requirements
�Java EE may be used to integrate systems� Applications written in different languages, like C++ or Microsoft®
Visual Basic� Applications running on different platforms, such as PCs or UNIX
workstations� Stand-alone Java-based applications that are not directly supported by
Java EE
�The interoperability requirements of Java EE make this possible� Java EE applications can connect to legacy systems using CORBA or
low-level socket interfaces� Java EE applications can connect to other Java EE applications across
multiple Java EE products
�Interoperability is achieved through the use of standard protocols for communication and data transfer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-27
Instructor Guide
Figure 5-14. J2EE Platform Roles RD8107.5
Notes:
15
Java EE platform roles� Java EE defines the following roles
�Java EE product provider� Implements a Java EE product that provides containers,
APIs, and other features�Application component provider
� Produces application building blocks (HTML documents, EJB components, JSP pages, and so forth)
� In many cases this role will be further subdivided�Application assembler
� Takes components developed by component providers and assembles them into a complete Java EE application
�Deployer� Deploys, configures, and runs EJB components and Web
applications�System administrator
� Configures and administers the infrastructure�Tool provider
� Provides application component development and packaging tools
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-29
Instructor Guide
Figure 5-15. J2EE Implementation RD8107.5
Notes:
Neither of these is very relevant to Java EE component developers.
The Java EE Software Development Kit can be downloaded from http://java.sun.com/javaee/downloads/index.jsp.
16
Java EE implementation� The Java EE Compatibility Test Suite
�Includes over 15,000 tests for Java EE 5.0�Tests a candidate platform for Java EE compatibility
� Checks that all of the necessary operations (for example, in required APIs) are possible
� Checks that the behavior of the APIs meets the specification� Checks end-to-end compatibility by performing operations on Java EE
components and back-end systems, and then checking the results
�Ensures portability between platforms� The Java EE Reference Implementation
�Provides an operational definition of the Java EE platform� The purpose is to validate the specification, and act as a reference for
Java EE platform providers
�Can be used by developers to confirm portability�Included as a binary with the Java EE SDK (free for
development and testing)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-31
Instructor Guide
Figure 5-16. Checkpoint RD8107.5
Notes:
Write down your answers here:
17
Checkpoint1. What do Java EE standard services offer?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
18
Checkpoint solutions1. A standardized way of accessing services that enterprise
applications require.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-33
Instructor Guide
Figure 5-17. Unit summary RD8107.5
Notes:
19
Unit summaryHaving completed this unit, you are able to:
�Describe the container services provided by Java EE�Discuss Java EE interoperability�List the Java EE platform roles�Discuss the Java EE implementation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 5. Java EE Container Services Overview 5-35
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 6. Servlet API (Part I)Estimated time
00:30
What this unit is about
The basics of the servlet API are presented here. This API contains the fundamental components of every servlet and Web application that is developed as part of Java EE platform.
In addition to understanding the life cycle of a servlet, you also understand how to process both GET and POST requests.
This unit also discusses some of the threading issues that need to be addressed by servlet developers.
What you should be able to do
After completing this unit, you should be able to:
• Understand the life cycle methods of a Java servlet
• Discuss how servlets:
- Process HTTP request parameters (for both GET and POST requests)
- Set the HTTP status code - Build the dynamic content for the response
How you will check your progress
Accountability:
• Checkpoint • Lab exercise
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
http://jcp.org/aboutJava/communityprocess/mrel/jsr154/index.html JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-1
Instructor Guide
Figure 6-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this unit, you will be able to:� Explain the lifecycle methods of a Java servlet� Describe how servlets:
� Process HTTP request parameters (for both GET and POSTrequests)
� Set the HTTP status code� Build the dynamic content for the response
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-3
Instructor Guide
Figure 6-2. Java Servlet Lifecycle RD8107.5
Notes:
The life cycle of a servlet is expressed in the Java Servlet API in the init, service (doGet() or doPost()), and destroy methods of the Servlet interface. This figure is a visual diagram of an individual servlet.
Creation:
• Servlets are loaded and instantiated when the container is started or when the container determines the servlets are needed to service requests.
Initialization:
• Initialization is required before a servlet can handle requests from clients.
• The init() method performs one-time activities, such as loading of servlet parameters, and initializes costly resources.
• There are two init() methods. One takes no input parameters, and one takes a ServletConfig reference as a parameter. The init() methods allow the servlet to access name-value pairs for the initialization parameters that are specific to that servlet. The
3
Create
Initialize
(Initialize failed)
Unavailablefor
service
(Unavailableexception thrown)
Availablefor
service
Servicingrequests
Unload
Destroy
Java servlet lifecycle
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
ServletConfig object gives access to the ServletContext object that describes information about the servlet environment.Request Handling:
• The servlet accepts client requests and send responses back via the Web server.
• service(), doGet(), doPost()... methods are called in response to clients (each HTTP request is on a different thread). The default service() method calls the doGet() method whenever an HTTP GET request is sent by the Web client (usually as a result of a URL), and the doPost() method whenever an HTTP POST request is sent by the Web browser client (usually as a result of an action in a HTML form).
End of Service:
• The Web container removes the servlet from service when the container needs to conserve memory resources or when it itself is being shut down.
• The container destroys and garbage collects the servlet, and calls the destroy() method.
• The destroy method should ensure that all servlet threads have completed, and should undo any initialization work that is not undone automatically by the destruction of the servlet.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-5
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — The HttpServlet.service()method is not usually overridden.
Transition statement — Next: The Java Servlet API
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-3. The Java Servlet API RD8107.5
Notes:
Various types defined in these packages are referenced in your servlets. Therefore, you typically import these types or their packages.
The classes and interfaces which make up the Servlet API are defined in two packages, javax.servlet and javax.servlet.http. WebSphere 7.0 supports Version 2.5 of the Servlet API.
Most servlets are used in a Web environment where HTTP is used between a Web client (a browser) and the Web server/application server. Much of the standard processing which must take place in this HTTP-based environment is managed by class javax.servlet.http.HttpServlet. A typical servlet extends this class and overrides one or more of the standard methods, for example, doGet() or doPost(), to supply servlet-specific behavior. This is analogous to the client-side model of extending java.applet.Applet and overriding init(), start(), and so forth.
4
The Java servlet API� The Servlet API is a set of Java classes that defines a
standard interface between a Web client and a Web server � The Servlet API includes two packages:
�javax.servlet
�javax.servlet.http
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Only HttpServletis covered in this course.
Transition statement — Next: ServletConfig and Initialization Parameters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-4. ServletConfig and Initialization Parameters RD8107.5
Notes:
The ServletConfig object allows access to the name-value initialization parameters from the Web application's configuration information. The configuration object also gives the servlet access to the ServletContext. The ServletContext describes the servlet's run-time environment. The HttpServlet class also implements the ServletConfig interface via its superclass, GenericServlet. As a result, you can call the getInitParameter() and getInitParameterNames() methods directory from the HttpServlet class.
The getInitParameter(String) method returns a String containing the value of the named initialization parameter.
The getInitParameterNames() method returns the names of the servlet's initialization parameters as an Enumeration of String objects.
The getServletContext() method returns a reference to the ServletContext in which the servlet is executing.
5
ServletConfig and initialization parameters� ServletConfig is used by the Web container to pass
information to the servlet during initialization� Accessed via a GenericServlet method
�getServletConfig
� ServletConfig:�Contains initialization parameters as a set of name-value
pairs
public String getInitParameter(String name)
public Enumeration getInitParameterNames
�Maintains a reference to the ServletContext object that gives the servlet information about the server
public ServletContext getServletContext
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Remind them that GenericServlet is a superclass of HttpServlet.
Transition statement — Next: Servlet Definition in web.xml file
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-5. Servlet Definition in web.xml file RD8107.5
Notes:
The above web.xml source file shows the encoding of the servlet initialization parameters. The code to handle these init parameters is shown on the next page.
6
<servlet>
<display-name>RegistrationServlet</display-name>
<servlet-name>RegistrationServlet</servlet-name>
<servlet-class>
com.ibm.exam.servlet.RegistrationServlet
</servlet-class>
<init-param>
<param-name>MaxTries</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>AutoSave</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationServlet</servlet-name>
<url-pattern>Register</url-pattern>
</servlet-mapping>
Servlet definition in web.xml file
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Example Servlet with Init Parameters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-6. Example Servlet with Init Parameters RD8107.5
Notes:
This servlet reads in the init parameters supplied by the web.xml file shown on the previous page.
There are two equivalent sets of code. The second explicitly invokes the getInitParameter() method on the ServletConfig object. In earlier versions of the Servlet API, this was the only way to get the initialization parameter values.
Note that you can get the ServletConfig object with the getServletConfig() method defined in Servlet.
7
// servlet's init method
public void init throws ServletException{
String maxTries;
String autoSave;
maxTries = getInitParameter("MaxTries");
autoSave = getInitParameter("AutoSave");
// process the parameters
...
}
or
// servlet's init method
public void init(ServletConfig config) throwsServletException{
String maxTries;
String autoSave;
maxTries = config.getInitParameter("MaxTries");
autoSave = config.getInitParameter("AutoSave");
// process the parameters
...
}
Example servlet with init parameters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Init parameter names are arbitrary and case-sensitive. These names should be coded as constants in the class. Note the fields being set are treated as read-only or single-assignment.
Transition statement — Next: HttpServlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-7. HttpServlet RD8107.5
Notes:
Class javax.servlet.http.HttpServlet is the base class for most servlets you will write. It provides an overloaded service method, and a set of doX() methods, where X corresponds to the HTTP request methods, for example, doGet(), doPost(), or doPut().
The overloaded service method's task is to look at the incoming HTTP request stream, determine the request method, and delegate to the corresponding specialized server handler. For example, doGet().
Subclasses of HttpServlet typically override doGet(), doPost(), or both, and possibly override init() or destroy(). There are additional do... methods as well. For example, doOptions(), doTrace(), doDelete() and doPut(), that correspond to other HTTP methods. However, doGet() and doPost() are the most commonly used.
8
HttpServlet� An HTTP-specific request handler� Adds HTTP specific methods:
�doGet: handle a GET request (URL)�doPost: handle a POST request (HTML form)
� Subclasses override the doGet, doPost, and other methods, and may override init and destroy
� Typically, doGet and doPost do the work, and are called by service
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Requests and Responses
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-8. Requests and Responses RD8107.5
Notes:
The abstract method:
void service (ServletRequest arg0, ServletResponse arg1)
defined in the Servlet Interface is implemented by HttpServlet. This method creates the corresponding HttpServletRequest and HttpServletResponse objects and dispatches an HttpServlet specific service method with signature:
void service (HttpServletRequest arg0, HttpServletResponse arg1)
The recurring tasks which are performed by most servlets are reading parameters which are part of the client HTTP request, and writing results back to the client as part of the HTTP response.
9
URL request
response
Application ServerWeb
ServerBrowser(client)
Servlet Instance
Requests and Responses� The service, doGet, and doPost methods each have two
parameters:�HttpServletRequest: provides access to request data
(parameters), HttpSession information, and so forth�HttpServletResponse: provides services to allow the
servlet to supply a response to the requesting client� Most servlet programming amounts to reading a request and
writing a response
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: HttpServletRequest
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-9. HttpServletRequest RD8107.5
Notes:
The HttpServletRequest object provided to the servlet encapsulates the incoming HttpRequest stream. It provides a means for viewing this data as a stream (getReader) or as individual properties. These properties include header, headerNames, cookies, method, requestURI, and servletPath.
The request object can also be used to store and retrieve per request attributes established for this servlet. These attributes are available through the setAttribute and getAttribute methods.
10
HttpServletRequest� Represents client's request� Contains getters for parts of the request:
�Request header, content type, length, method�Request URL as a String and request servlet path�Client security type�Request parameters
� A scope for object sharing between participantsin the request
POST /Music/SearchServlet HTTP/1.1Accept: */*Referer: http://www.music.ibm.com/Music/musicSearch.htmlAccept-Language: en-usContent-Type: application/x-www-form-urlencodedUA-CPU: x86Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; …)Host: localhost:9080Content-Length: 50Connection: Keep-AliveCache-Control: no-cache
song_title=Hello&song_artist=Jones&limit_number=20
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Request Protocol
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-10. Request Protocol RD8107.5
Notes:
The request parameter set is populated with the aggregation of both the query string parameters and post body parameters. The order of this aggregation is that query string parameter data takes precedence over post body parameter data. When a query string and post body both have the same name, the values appear as multiple values for the same name.
Posted form data is only read from the input stream of the request and used to populate the parameter set when all of the following conditions are met:
• The request is an HTTP or HTTPS request.
• The HTTP request is a POST request.
• The content type of the request is application/x-www-form-urlencoded.
• The servlet calls any of the getParameter methods against the input request object.
If one or more of the above conditions is not true, the posted data is available to be read via the request object's input stream.
11
Request protocol� The request object encapsulates all of the information from the
client request. The following methods are available to access parameters:�getParameterNames
� Returns an Enumeration of parameters on the HTML page�getParameterValues(String name)
� Returns the value of a multivalued parameter�getParameter(String name)
� Returns the value of a specific named parameter�getReader
� Returns a BufferedReader to view input
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-21
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — getParameter() returns the value, the first value of an array of values, or null if no value is supplied. getParameterValues() returns the array or null.
Transition statement — Next: Example HTML Form
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-11. Example HTML Form RD8107.5
Notes:
To demonstrate handling of FORM data by a servlet, look at an example HTML form and then look at a servlet which responds to the form submission. Here is the HTML form. Note the ACTION attribute specifies a URI which invokes your servlet when the form is submitted.
12
<P>Use this form to search for the music you want.
<FORM METHOD="POST" ACTION="/Music/SearchServlet">
<P>Please enter your search criteria:
<P>Song title:
<INPUT NAME="song_title" TYPE="TEXT" SIZE="12" MAXLENGTH="20">
<P>Song artist:
<INPUT NAME="song_artist" TYPE="TEXT" SIZE="15" MAXLENGTH="25">
<P>Thank you!
<INPUT TYPE="SUBMIT">
<INPUT TYPE="RESET">
</FORM>
Example HTML form
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-23
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Reading a Post
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-12. Reading a Post RD8107.5
Notes:
There are two parameters that were coded on the form on the previous page. The first one has a name of song_title and the second one has a name of song_artist.
When processing a form, you can pull the parameters by name or you can enumerate through all of the parameters and pull off the ones you need. Often you hard-code the parameter names in your code, but in general that should be avoided. Using a properties file and a properties (dictionary) will keep your code more flexible.
To pull the value directly, you could use the following code:
String title = req.getParameter(”song_title”);
13
public class SearchServlet extends HttpServlet {
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
...
Enumeration enum = req.getParameterNames;
while (enum.hasMoreElements) {
String name = (String) enum.nextElement;
String value = req.getParameter(name);
//… do something with each pair...
}
...
}
}
Reading a post
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: HttpServletResponse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-13. HttpServletResponse RD8107.5
Notes:
The response object encapsulates all information to be returned from the server to the client. In HTTP protocol, this information is transmitted from the Web server or application server back to the client in the HTTP headers and in the document portion of the response.
This object can also be used to send a redirection directive back to the browser instead of actual content.
14
HttpServletResponse� Represents communication channel back to client� Sets the content type and status code� Sets content headers (cookies, caching, and so forth)� Allows the servlet to return dynamic content or error
information� Allows the servlet to redirect the client to another URL
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Response Protocol
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-14. Response Protocol RD8107.5
Notes:
One key method in the HttpServletResponse is the getWriter() method. The dynamic content of your servlet is written to the PrintWriter and returned to the client Web browser. This output is typically a dynamically generated HTML or XML document.
MIME is Multipurpose Internet Mail Extensions. MIME types include text/html, text/xml, and image/jpeg, for example.
15
Response protocol� setContentType(String type)
�Set the content type for this response�Type is a MIME type
� getWriter
�Returns a reference to the PrintWriter� getOutputStream
�Returns a reference to the ServletOutputStream�Used to create binary documents
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-29
Instructor Guide
Instructor notes:
Purpose —
Details — The content type defaults to text/html.
Additional information —
Transition statement — Next: Setting the Status Code
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-15. Setting the Status Code RD8107.5
Notes:
The HTTP specification can be found at http://www.w3.org (in RFC 2616).
Common status codes are 200 (OK) and 404 (not found). The corresponding constants are HttpServletResponse.SC_OK and SC_NOT_FOUND.
16
Setting the status code� Your response must contain a status code� Status codes for HTTP 1.1
� 1xx: Informational – Request received, continuing process (the client needs to respond in some way)
� 2xx: Success – The action was successful� HttpServletResponse.SC_OK
� 3xx: Redirection – Further action must be taken in order to complete the request� See also the HttpServletResponse.sendRedirect method
� 4xx: Client error – The request contains bad syntax or some other client error
� 5xx: Server error – The request is valid, but the server failed to fulfill the request
� HttpServletResponse has constants beginning with SC_ for the standard status codes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-31
Instructor Guide
Instructor notes:
Purpose —
Details — The status code defaults to 200.
Additional information —
Transition statement — Next: Simple Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-16. Simple Servlet RD8107.5
Notes:
This is a simple servlet that returns some HTML to the requester. It has three parts:
• Set the content type and status code
• Get a PrintWriter
• Write to the PrintWriter
17
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
// get stream to output HTML on!
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType("text/html");
PrintWriter out = res.getWriter;
// send out a simple banner
out.println("<HTML><BODY><H1>Today is "+(new Date));
out.println("</H1></BODY></HTML>");
}
}
Simple servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — A better way to generate HTML is to use JSPs, which will be covered later.
Transition statement — Next: Processing an HTTP Request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-17. Processing an HTTP Request RD8107.5
Notes:
18
Processing an HTTP request� General flow of processing an HTTP request
�Process input (forms) data�Process input headers�Initiate and do the business work�Set status code�Set response headers�Output document
� Note that you must set the status code and headers before any of the output document is actually sent back to the client�If the PrintWriter is buffered, the status code and response
headers have to be set before the buffer is flushed� If you are going to redirect the HTTP request to another URL,
you must do this before any of the document has been returned to the client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-35
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Processing Input Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-18. Processing Input Data RD8107.5
Notes:
The servlet APIs take care of the parsing, multiple and missing values, the location of the data, and the decoding of the values automatically.
The HttpServletRequest.getInputStream method returns a ServletInputStream that can be used to read in the POSTed data in raw format. This is needed when implementing your own private protocol (between an applet and a servlet, for example).
19
Processing input data� Form data or query data is sent from the Web browser to the
Web server�For a GET, form data is passed with request string, that is, �http://www.ilscs01.ibm.com/MyServlet?name=jane+Doe �For a POST, data passed as a part of the request body
� Fields and values are separated by & and =� Query data is encoded and must be decoded before it can be
processed:�The text:
name=Margaret Vogel&age=7 1/2 yearsis encoded as:name=Margaret+Vogel&age=7+1%2F2+years
�Values can be omitted or duplicated:height=49in&name=&height=125cm
� The Servlet APIs do the work of decoding all this for you
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-37
Instructor Guide
Instructor notes:
Purpose —
Details — Note that in the second data example, name has no value and height occurs twice.
Additional information —
Transition statement — Next: Processing Input Data Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-19. Processing Input Data Example RD8107.5
Notes:
The assumption here is that processRequest was called from doGet and doPost. The status needs to be set before the document has been written to the PrintWriter.
If the name parameter is not passed to the servlet as query data, null is returned by the getParameter call. Also, if no height parameter is specified, null is returned by the getParameterValues method.
If name= is passed, then the value for name is a String of length 0. If height= is passed, then height returns an array of one element. That element contains a String of length 0.
If the following query data is supplied,
height=125cm.&name=Margaret&height=49in.
then the value for String name is Margaret. The height array contains two values. The value for height[0] is 125cm. and height[1] is 49in.
20
public void processRequest(HttpServletRequest request,
HttpServletResponse response) throws... {
// Called from doGet and doPost
// Name should have only one value and height is
// expected to have multiple values
String name = request.getParameter("name");
if (name==null) {
name = "unknown";
} else if (name.length== 0) {
name = "missing";
}
String height[] = request.getParameterValues("height");
if (height == null) {
height = new String[] {"unknown"};
}
for (int i = 0; i < height.length; i++){
if (height[i].length== 0) height[i] = "missing";
}
// now process the request headers, set status and response
// headers and build the output document ...
}
Processing input data example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-39
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Another way to deal with a parameter having no value is to have the field be checked by JavaScript in the browser before the request is sent.
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-20. Checkpoint RD8107.5
Notes:
Write down your answers here:
21
Checkpoint 1. How does a Java Servlet use the HttpServletRequest
and HttpServletResponse classes?2. What methods are involved in the lifecycle of a Java
Servlet?3. What must your servlet do to process input parameters
from a GET and POST request?4. How do you set the status for a response?5. How do you build the output document?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-41
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint Solutions
22
Checkpoint solutions (1 of 2)1. The HttpServletRequest contains information from the
client’s HTTP request. The information is usually parsed for you, and is available via getter methods. This information includes the various headers, cookies, and passed parameter values.HttpServletResponse provides a way to set values to be included in the response to the client. This includes the header values, cookies, and the output HTML document.
2. Lifecycle methods:• init performs any initialization tasks• service invokes the appropriate doGet and doPost
methods• destroy performs any termination task
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 6-21. Unit summary RD8107.5
Notes:
23
Checkpoint solutions (2 of 2)3. The servlet needs to call the getParameter or
getParameterValues methods. The getParameterValues method returns an array of String objects.
4. response.setStatus(int code). You can use the constants in HttpResponse to set the code as well.
5. You get the PrintWriter from the HttpServletResponseobject that was passed to your servlet. Anything you write to this PrintWriter is in your output document. You must redirect or forward requests before you have written to the PrintWriter.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 6. Servlet API (Part I) 6-43
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 7. Library Case Study FlowEstimated time
00:15
What this unit is about
This unit describes the library case study used in the lab exercises.
What you should be able to do
After completing this unit, you should be able to:
• Describe the key entities in the library case study
• Distinguish between the layers used to describe the entities
• Describe the object model of the library case study
• State the purpose of the use cases described
How you will check your progress
Accountability:
Lab exercises
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-1
Instructor Guide
Figure 7-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this unit, you will be able to:
�Describe the key entities in the library case study�Distinguish between the layers used to describe the entities�Describe the object model of the library case study�State the purpose of the use cases described
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Additional information on the design of the case study, including UML diagrams, is available as an Appendix to the lab exercises entitled “Case Study Design”.
Transition statement — Next: Library Case Study
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-3
Instructor Guide
Figure 7-2. Library Case Study RD8107.5
Notes:
3
Library case study� Follows a library computer system scenario� Used by both librarians and patrons� Library system keeps track of:
�Items in the library�Number of copies of each item�Patrons registered with the system�Loan of items to patrons
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Key Entities
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-5
Instructor Guide
Figure 7-3. Key Entities RD8107.5
Notes:
4
Key entities� Patron
�Typically visits the library to take out copies of items on a loan
� Item�An item stocked by the library
� Book, video, DVD, and so on� Copy
�Each item has a number of physical copies� For example, the library may
stock five copies of a book� Loaned Copy
�A copy of an item can be taken out on loan by a patron for a specified loan period
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Patron
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-7
Instructor Guide
Figure 7-4. Patron RD8107.5
Notes:
5
Patron� A Patron has the following attributes:
�Unique key� A system-generated identifier
�First name�Last name�Password
� Used to log in to a library system
�E-mail address
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Item
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-9
Instructor Guide
Figure 7-5. Item RD8107.5
Notes:
6
Item� An Item has the following attributes:
�Unique key�Title�Author�Volumes�Publish date�ISBN equivalent�Type
� Books� Audio books� CDs� DVDs� Video� Other
�Oversize� Standard size or oversized
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Copies
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-11
Instructor Guide
Figure 7-6. Copies RD8107.5
Notes:
7
Copies� A Copy has the following attributes:
�A unique number�Item ID
� Every Copy is a copy of a specific Item�Loanable
� Not all copies can be loaned
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: On Loan
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-13
Instructor Guide
Figure 7-7. Loaned Copy RD8107.5
Notes:
8
Loaned copy� Loaned copy has the following attributes:
�Patron ID� Patron who has the copy on loan
�Item key� The item loaned
�Copy number� The specific copy of an item loaned
�Due date�Times renewed
� The number of times a patron has renewed this loan
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Layers: Model, Data Store, Database
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-15
Instructor Guide
Figure 7-8. Layers: Model, Data Store, Database RD8107.5
Notes:
This shows how Patron and Item are divided into layers. The Patron and Item model class reflect the Patron and Item entities themselves (package com.ibm.ils.library.model). A similar structure is used for the Copy entity.
The middle layer offers two ways of working with the underlying database table. Either a CMP entity bean (package com.ibm.ils.library.ejb) can be used, or a data store class (package com.ibm.ils.library.datastore.jdbc), which uses JDBC to communicate with the database table. The data is persisted in these database tables.
9
Layers: model, data store, and database
PATRONdatabase table
ITEMdatabase table
Patronmodel class
Itemmodel class
PatronEJBCMP
PatronDataStore(JDBC)
ItemEJBCMP
ItemDataStore(JDBC)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Object Model
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-17
Instructor Guide
Figure 7-9. Object Model RD8107.5
Notes:
The class diagram for the case study shows the relationships between the major entities, as well as their attributes and behaviors. The LoanedCopy object is intended to be a value object which represents a copy that has be loaned to a patron; it is returned from the model layer to the controller layer for use in display to the end user.
10
Object model
+renew(in list : Collection)+add()+retrieveLoanedCopies() : Collection+remove()+update()
-id : int-firstName : String-lastName : String-email : String
Patron
+add()+remove()+update()
-id : int-medium : char-isbnEquivalnet : String-title : String-author : String-oversize : boolean-volume : int-published : Date
Item
+add()+remove()+renew()+update()
-loanable : boolean-due : Date-itemId : int-patronId : int-timesRenewed : int-copyNumber : int
Copy-author : String-copyNumber : int-due : Date-itemId : int-renewAccomplished : boolean-renewMessage : String-renewRequested : boolean
LoanedCopy
*0..*
borrows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Use Case: Patron Login
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-19
Instructor Guide
Figure 7-10. Use Case: Patron Login RD8107.5
Notes:
Main success scenario:
1. Patron asks system to display login form.
2. System displays the form.
3. Patron enters patron ID (created during the Register New Patron use case) and password and transmits to the system.
4. System verifies the patron's patron ID and password.
5. System displays Welcome form with a menu of valid actions.
11
Use case: patron login� Triggers:
�Patron wants to interact with the library system� Primary actors:
�Patron� Preconditions:
�Patron has registered� Success end conditions:
�Patron has logged in� Failed end conditions:
�Patron is not logged in� Patron ID or password is incorrect
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Use Case: List Checked Out Items
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-21
Instructor Guide
Figure 7-11. Use Case: List Checked Out Items RD8107.5
Notes:
Main success scenario:
1. Patron asks system to display a list of items the patron has on loan.
2. System displays the List of Checked Out Items form to the patron.
12
Use case: list checked out items� Triggers:
�Patron requests a listing of the items that the patron has on loan� Primary actors:
�Patron� Preconditions:
�Patron has already logged in� Success end conditions:
�Checked out items (if any) are displayed�If no items are checked out, a message is sent to the patron
� Failed end conditions:�Patron is not logged in
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Use Case: Renew Checked Out Items
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-23
Instructor Guide
Figure 7-12. Use Case: Renew Checked Out Items RD8107.5
Notes:
Main success scenario:
1. Patron selects (on the List of Checked Out Items form) which items the patron wishes to renew and transmits those selections to the system.
2. The system verifies that no fines are outstanding.
3. The system verifies that each item is not currently reserved.
4. The system verifies that each item is renewable and has been renewed less than the maximum number of times (maximum is three times).
5. The system updates the due date for each item to be renewed (current date plus three weeks).
6. The system displays the List of Checked Out Items form with updated information (and warning messages, if any).
13
Use case: renew checked out items� Triggers:
�Patron wants to renew items� Primary actors:
�Patron� Preconditions:
�System has listed the patron's currently checked out items� Success end conditions:
�Selected items were renewed� Failed end conditions:
�No items were selected for renewal�Not all items were renewed due to fines or renewal limit
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Use Case: Register New Patron
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-25
Instructor Guide
Figure 7-13. Use Case: Register New Patron RD8107.5
Notes:
Main success scenario:
1. Librarian asks system to display the Register Patron form.
2. System displays the form.
3. Librarian enters patron's e-mail address, first name, last name, and password into the form and transmits it to the system.
4. System generates a patron ID for the patron (for example, using date, time, and user name).
5. System adds new patron in the database.
6. System displays Registration Success form to Librarian, including system-generated patron id for that patron.
14
Use case: register new patron� Triggers:
�A new patron arrives at the registration desk
� Primary actors:�Librarian
� Preconditions:�Librarian has already been
authenticated� Success end conditions:
�Patron is registered with the system (can now loan items)
� Failed end conditions:�Patron was not registered with
the system�Patron is already registered with
the system
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Use Case: Add Item to Collection
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-27
Instructor Guide
Figure 7-14. Use Case: Add Item to Collection RD8107.5
Notes:
Main success scenario:
1. Librarian asks system to display the form for adding an item.
2. System displays the form.
3. Librarian enters item's title, author, year of publication, type of item (book, CD, audio tape, DVD, and so forth), oversize (used to determine the position of the book in the library: special shelves for big books or box sets of CDs), number (the number of physical things that make up the item -- a CD item may have two CDs while an audio tape item may have five tapes), and ISBN number into the form and transmits it.
4. System adds item to the collection.
5. System displays Item successfully added form to librarian.
6. This use case is currently not implemented in the exercises.
15
Use case: add item to collection� Triggers:
�Clerk hands librarian a new item� Primary actors:
�Librarian� Preconditions:
�Librarian has already been authenticated� Success end conditions:
�Item was added to the collection� Failed end conditions:
�Item was not added to the collection
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-29
Instructor Guide
Figure 7-15. Unit summary RD8107.5
Notes:
16
Unit summary� Having completed this unit, you are able to:
�Identify the key entities in the library case study�Explain the layers used to describe the entities�Identify the object model of the library case study�Discuss the use cases for the library case study
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 7. Library Case Study Flow 7-31
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 8. JavaServer Pages OverviewEstimated time
00:30
What this unit is about
This unit describes the need for server-side scripting and how JavaServer Pages (JSPs) provide this support for your Web applications.
What you should be able to do
After completing this unit, you should be able to:
• Explain JavaServer Pages technology
• Identify the role of JSP within Web applications
• Explain the JSP Execution Model
• Explain the JSP Life cycle
How you will check your progress
Accountability:
• Checkpoint • Lab exercise
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v 5.0 API Specifications
http://jcp.org/aboutJava/communityprocess/final/jsr245/index.html JSR-000245 JavaServer Pages 2.1 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-1
Instructor Guide
Figure 8-1. Unit objectives RD8107.5
Notes:
The purpose of this topic is to provide an initial motivation and introduction to JavaServer Pages (JSP).
2
Unit objectives� After completing this unit, you will be able to:
�Explain JavaServer Pages technology�Identify the role of JSP pages within Web applications�Describe the JSP execution model�Discuss the JSP lifecycle
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Content within a Web Page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-3
Instructor Guide
Figure 8-2. Content within a Web Page RD8107.5
Notes:
Each document which makes up a Web Site or Web Application typically comprises both static and dynamic content.
Dynamic content is targeted to the current client viewing the site.
Page layout is generally performed by the client browser, and thus its rules are expressed in a Markup Language (typically HTML).
XSL - Extensible Style Language, a transformation language and a formatting language used to automate the conversion of one XML document into another XML document.
3
Atomic Bank and Trust Inc.
Loan ID 00000040
Account 1234-50-1278
Amount 103.52
Principal 37.50
Interest 74.02
save submitToday's News* Atomic Bank Announces Fourth Quarter Results
| Home | Search | Products | Copyright | Trademarks
Dynamic Content
Content within a Web page� Content delivered to a client is composed of:
�Static or non-customized content�Customized content
� Page layout and style are managed through HTML and XSL
Static Content
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: What Is a JavaServer Page?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-5
Instructor Guide
Figure 8-3. What Is JavaServer Pages? RD8107.5
Notes:
The first JSP Specification became available in June 1999. The current version, JSP 2.1, is part of Java EE Specification 5.0.
4
What is JavaServer Pages technology?� JavaServer Pages technology that lets you mix static HTML
with dynamically-generated HTML� JSP technology allows server-side scripting:
�Static tags are HTML, XML, or another markup language.�Dynamic content generated by scripting code
� Java is the (default) scripting language
� A JSP file (with an extension of .jsp) contains any combination of:�JSP syntax�Markup tags such as HTML or XML
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Mention that another example of server-side scripting is Microsoft's Active Server Pages (ASP).
Transition statement — Next: JSP Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-7
Instructor Guide
Figure 8-4. JSP Example RD8107.5
Notes:
5
JSP example<HTML>
<HEAD><TITLE>Our WebSite Home</TITLE></HEAD>
<BODY background="image.jpg"
text="#ffffff">
<TABLE>
<TR><TD>
<H1>Welcome to Our WebSite</H1>
</TD></TR><TR><TD>
<H3>Today's date is
<%= new java.util.Date() %>
</H3></TD>
<TD>see <A href="breaking.html">
breaking news</A>.
</TD></TR>
</TABLE>
</BODY>
</HTML>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Syntax Elements
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-9
Instructor Guide
Figure 8-5. JSP Syntax Elements RD8107.5
Notes:
JSP Expression Languages (EL) provides an alternative to Java expressions. This is covered in Unit 21.
6
JSP syntax elements� JSP 2.0 syntax consists of:
�Directives� Instructions to the JSP engine or compiler
�Scripting� Declarations – additional methods and variables to be generated into
the JSP servlet� Scriptlets – inline Java code� Expressions – Java code that resolves to Strings
�Actions available within the JSP servlet� Standard actions for bean usage and flow control� Custom actions can be added
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSPs or Servlets?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-11
Instructor Guide
Figure 8-6. JSP or Servlet? RD8107.5
Notes:
It is true that both servlets and JSP pages have many features in common, and can be used for serving dynamic Web content. In fact, JSPs are ultimately compiled into servlets (though this happens invisibly). Naturally, this may cause some confusion as to when to opt for one of the technologies over the other. Luckily, Sun's Java EE Blueprints offers some guidelines towards this.
According to the Blueprints, use servlets strictly as a Web server extension technology. This could include the implementation of specialized controller components offering services like authentication, database validation, and so forth. It is interesting to note that what is commonly known as the JSP engine itself is a specialized servlet running under the control of the web container. Since JSP only deals with textual data, you have to continue to use servlets when communicating with Java applets and applications.
JSP should also be used in place of proprietary Web server extensions, like server-side includes, as it offers excellent features for handling repetitive content.
7
JSP or servlet?� Use servlets to:
�Determine what processing is needed to satisfy the request�Validate input�Work with business objects to access the data and perform
the processing needed to satisfy the request�Control the flow through a Web application
� Use JSP pages for displaying the content generated by your Web application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Be sure to stress the view and controller natures of JSP pages and servlets.
Transition statement — Next: JSP Benefits (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-13
Instructor Guide
Figure 8-7. JSP Benefits (1 of 2) RD8107.5
Notes:
With servlets, the logic for generation of the dynamic content is an intrinsic part of the servlet itself, and is closely tied to the static presentation templates responsible for the user interface. Thus, even minor changes made to the UI typically result in the recompilation of the servlet. This tight coupling of presentation and content results in brittle, inflexible applications.
With JSP, the logic to generate the dynamic content is kept separate from the static presentation in external components, which are used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the Web server by the JSP engine.
8
JSP benefits (1 of 2)� Separation of static from dynamic content
�The logic to generate the dynamic content is kept separate from the static presentation by encapsulating it within external (JavaBeans) components
�Separation of workload� Write once, run anywhere
�Easily moved between platforms, no rewriting necessary� Java EE-Compliant
�The Java EE Blueprint recommends using JSP pages over servlets for the presentation of dynamic data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Benefits (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-15
Instructor Guide
Figure 8-8. JSP Benefits (2 of 2) RD8107.5
Notes:
9
JSP benefits (2 of 2)� Leverages the Servlet API
�The JSP specification is a standard extension defined on top of the Servlet API
� Reuse of components and tag libraries�JSP technology emphasizes the use of reusable
components such as JavaBeans, Enterprise JavaBeans, and tag libraries
� High-quality tool support�One goal of the JSP design is to enable the creation of JSP
development tools, such as Page Designer in Application Developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Execution Model (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-17
Instructor Guide
Figure 8-9. JSP Execution Model (1 of 2) RD8107.5
Notes:
Before we look at the syntax of JSP, one needs to understand the difference between the design-time model of JSP and the run-time model. Typically, the run-time artifact of a JSP page is a servlet. There is a transformation, which takes place between the design-time JSP source file, and the runtime servlet code. A JSP Page compiler handles this conversion. Its purpose is to parse the JSP source, generate code for a run-time artifact (a servlet), and prepare the code for execution (compile the servlet class). This parsing, code generation, compilation need only be performed once (if .jsp file does not change).
The loading and execution is a separate step that follows normal Servlet loading and execution rules. If the JSP servlet is currently loaded, and a request for the JSP page is made, the JSP servlet's service method is invoked. If the JSP Servlet exists (.class file) but is not yet loaded, it is loaded and then its service method is invoked.
10
JSP execution model (1 of 2)� A JSP page is executed in a Web container
�The Web container delivers client requests to the JSP page, and returns the page's response to the client
� The JSP page is converted into a servlet (JSP servlet) and executed
� This process is known as page compilation:�JSP source is parsed�Java servlet code is generated�This JSP servlet is compiled, loaded, and run
JavaServer Page
Page Compilation Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Execution Model (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-19
Instructor Guide
Figure 8-10. JSP Execution Model (2 of 2) RD8107.5
Notes:
The decision to recompile is based on the timestamps of the generated JSP servlet and the .jsp source file.
A JSP page request with a request parameter named jsp_precompile is a precompilation request. The value of the jsp_precompile parameter may be true, false, or unspecified.
To precompile the Simple-jsp, you could code:
http://host/Simple.jsp?jsp_precompile = True
11
JSP execution model (2 of 2)� Compilation is only performed as needed:
�No class file exists, or�JSP has been updated since last compilation
� Precompilation�The JSP 2.0 specification requires support by the container
for precompilation� All request parameters starting with jsp_ are reserved
�JSP pages should ignore parameters starting with jsp_
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The JSP Life Cycle
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-21
Instructor Guide
Figure 8-11. The JSP Lifecycle RD8107.5
Notes:
12
Create
Initialize
(Initialize failed)
Unavailablefor
service
(Unavailableexception thrown)
Availablefor
service
Servicingrequests
Unload
Destroy
The JSP lifecycle� JSP files are compiled
into servlets and have the same lifecycle as all other servlets
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — This is the same life cycle that you saw for servlets in a previous unit.
Additional information —
Transition statement — Next: Typical JSP Access Model
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-23
Instructor Guide
Figure 8-12. Typical JSP Access Model RD8107.5
Notes:
This access model facilitates separating content generation from content display.
The HTTP request comes in from the Web client, and passes through the Web server to the application server. The servlet's service() method is invoked.
The servlet interacts with Java classes (JavaBeans, the business objects) to process the request. The JavaBeans may access a back-end EIS (Enterprise Information System). The dynamic content is placed into another JavaBean that is to be shared with a JSP page via one of the standard scopes (see more about scope in later paragraphs of this note). In this example the request scope is assumed.
The servlet forwards the request to the JSP page. If this is the first request for the JSP page, it is compiled into a servlet. In any case, the JSP servlet's service() method is invoked.
The JSP servlet gets the shared object from the appropriate scope (the request scope in this example).
13
(View) JSP
MVC Design Pattern
Web Container
EIS
Request
Response
(Model) JavaBean
1
2
3
4
5
Bro
wse
r
(Controller) Servlet
Typical JSP access model� The request is sent to a servlet that generates dynamic
content, and calls a JSP page to send the content to the browser, as shown:
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Finally, the JSP servlet generates the dynamic content and returns the generated Web page to the Web client.The processing is divided between presentation and front components. Presentation components are JSP pages that generate the HTML or XML response that determines the user interface when rendered by the browser. Front components (also known as controllers) do not handle any presentation issues but instead process the HTTP requests. Here they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the user's actions, which presentation component to forward the request to.
As discussed, the servlet places the model component in an attribute of an object that it can share with the JSP page and then transfers control to the page. The particular techniques used to transfer control between servlet and JSP is discussed in Unit 11.
Objects that are typically used to hold the model component are a HttpServletRequest, HttpSession, or ServletContext object. From the viewpoint of the JSP page, each of these objects is associated with a scope. For example, HttpServletRequest is associated with request scope, HttpSession with session scope, and ServletContext with application scope. Each scope has a different life cycle and degree of sharing with other application components that make them suitable for sharing particular types of objects or data.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Subsequent JSP Requests
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 8-13. Subsequent JSP Requests RD8107.5
Notes:
14
Subsequent JSP requests� Next time the JSP page is
requested:�The JSP Web container
determines whether the .jspfile has changed since it was loaded� If changed, the Web container
recompiles the page, loads the newly generated servlet, and then invokes the servicemethod
� If it has not changed, the current instance is used, and the service method is called
�The rest of the processing is unchanged
(View) JSP
(Model) JavaBean
(Controller) Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Page Compilation in WebSphere
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 8-14. Page Compilation in WebSphere RD8107.5
Notes:
15
Page compilation in WebSphere� JSP parsing and code generation is provided by a Page
Compilation servlet� IBM WebSphere Application Server Version 7.0 supports the
JSP 2.1 specifications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: JSP Servlet Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 8-15. JSP Servlet Class RD8107.5
Notes:
There is a corresponding JspPage Interface for non-Http based JSPs (not very common).
In addition to the HttpJspPage Interface and the _jspService method, the _jspService method is generated for you by the Web Container. The JSP specification defines two additional methods, jspInit and jspDestroy. These methods can be overridden within your JSP to affect the behavior of the initialization and destruction life cycle methods of the generated servlet. The jspInit and jspDestroy methods can be specified in a JSP Declaration.
The JspWriter output is fed to the servlet's response stream.
16
JSP servlet class
� Class (servlet) that is created by the Page Compiler must implement the HttpJspPage interface
� This interface defines the _jspService method where script content is written
void _jspService(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
� A JSP page may include initialization and cleanup routinespublic void jspInit()
public void jspDestroy()
� Output is written to a JspWriter, which supports buffer management
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Scope Attributes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 8-16. Scope Attributes RD8107.5
Notes:
A JSP page can create or access Java objects when processing a request. Created objects have a scope attribute defining where there is a reference to that object and when the reference is removed.
Many action tags have a scope attribute. The value of this scope can be one of four values:
• Page scope has the shortest lifespan; even if the request is forwarded to another page, the object reference is lost. Think of a variable that has page scope as a local variable.
• Request scope extends for the life of a single request, from the time it is first received by the server until a response has been returned to the client. This allows any forwarded and included pages to access the object (using request.getAttribute() and request.setAttribute()).
• Session scope allows references to be shared across the current user's session (using session.getAttribute() and session.setAttribute()).
• Application scope allows references to be shared across the entire application (using application.getAttribute() and application.setAttribute()).
17
Scope attributes� A JSP page can access objects at run time via one of four
different scopes (or holder objects)�Page
� The current JSP page, used with Custom Actions
�Request� The current HttpServletRequest object
�Session� The current HttpSession object
�Application� The current ServletContext object
applicationsession
requestpage
Scope Duration
session
page
application
request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-33
Instructor Guide
Scopes are not nested, but their lifespans are.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Emphasize that the diagram on this and the following slides depicts the nested lifespansof the various scopes, not the nesting of the scopes themselves.
Transition statement — Next: Page Scope
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-35
Instructor Guide
Figure 8-17. Page Scope RD8107.5
Notes:
Page scope is the default.
18
Page scope� Objects are available only within the page where they are
created� References to these objects are released after the response is
sent back to the client, or when the request is forwarded to somewhere else
� Use setAttribute(String, Object) to set andgetAttribute(String) to retrieve
� References to objects with page scopeare stored in the pageContext object application
session
requestpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Request Scope
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-37
Instructor Guide
Figure 8-18. Request Scope RD8107.5
Notes:
The request scope is a convenient bucket to permit a servlet controller to pass along object references to the JSP. Such references are available for garbage collection at the completion of the current HTTP request. Contrast this with the lifetime of references placed on the current session. You can directly use the getAttribute and setAttribute methods of the HttpServletRequest object.
19
Request scope� Objects are available within the page where they are created, and
pages to which the current request is forwarded� References to these objects are released after the response is sent
back to the client� References to objects with request scope are stored in the request
object� To store objects in the request context:
�Use req.setAttribute(String, Object)in the servlet� req is the parameter of typeHttpServletRequest that is passedto the servlet
�In a JSP page, userequest.getAttribute(name)to retrieve values
applicationsession
requestpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Be sure students understand that the parameter may not be called req. For example, it is called arg0in wizard-generated servlets.
Transition statement — Next: Session Scope
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-39
Instructor Guide
Figure 8-19. Session Scope RD8107.5
Notes:
20
Session scope� Objects are available from servlets and JSP pages processing
requests that are in the same user session� References to the object are released after the associated
session ends� References to objects with session scope are stored in the session object
� To store objects in the session context:�In the servlet, use code such as:
HttpSession session
= req.getSession;
session.setAttribute(name, object);
�In a JSP page, usesession.getAttribute(name)to retrieve values
applicationsession
requestpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Application Scope
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-41
Instructor Guide
Figure 8-20. Application Scope RD8107.5
Notes:
21
Application scope� Objects are available from servlets and pages that are processing
requests in the same application� References to the object are released when the run-time
environment reclaims the ServletContext object� References to objects with application scope are stored in the application object
� To store objects in the application context:�In the servlet, use code such as:
ServletContext context =
getServletContext;
context.setAttribute(name, object);
�In a JSP page, useapplication.getAttribute(name)to retrieve values
applicationsession
requestpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Positioning
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-43
Instructor Guide
Figure 8-21. JSP Positioning RD8107.5
Notes:
JSP pages provide an easy way to embed Java code within HTML file to script the insertion of dynamic content.
There are some potential problems, however, which result from the way in which JSPs are used and developed. Presentation from business logic should be cleanly separated. Thus, JSPs should not include any business logic.
The PageDesigner role should own JSP pages. This requires page development tools which make this possible.
JSP pages should contain a minimal quantity of Java code. Beware of server-side scripting source files dominated by script (that is, where HTML consumes a minority portion of the file).
22
JSP positioning� Advantages:
�Can use page authoring tools to develop presentation�Allows HTML framework to manage composition of content�Full support for Java on server-side
� Warnings:�Potential to write too much Java code in the HTML
document�Potential to use for more than just presentation (view)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-45
Instructor Guide
Figure 8-22. Checkpoint RD8107.5
Notes:
Write down your answers here:
23
Checkpoint1. What types of content are most Web pages composed of?2. What are the disadvantages of using servlets for Web
pages?3. What executes when a JSP page is invoked?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
24
Checkpoint solutions1. Web pages are composed of static elements that are the
same for every client, and dynamic elements that are built dynamically according to input from the client.
2. Coding the HTML output text in the servlet requires servlet developers to know Web page design as well as Java. Since both Java and HTML are in the servlet, a simple Web page change requires that you change the servlet.
3. Ultimately, a JSP source file is compiled into a servlet, which is what is executed at run time.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-47
Instructor Guide
Figure 8-23. Unit summary RD8107.5
Notes:
25
Unit summary� Having completed this unit, you are able to:
�Explain JavaServer Pages technology�Identify the role of JSP pages within Web applications�Describe the JSP execution model�Discuss the JSP lifecycle
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 8. JavaServer Pages Overview 8-49
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 9. JavaServer Pages Specification and SyntaxEstimated time
01:00
What this unit is about
This unit describes the basic syntax needed to build JSP pages.
What you should be able to do
After completing this unit, you should be able to:
• Write JSP pages using the core JSP syntax
- Directives
- Declarations
- Scriptlets
- Expressions
• Describe the general content of a JSP page
• Describe how to generate XML from a JSP document
• Identify the XML syntax for JSP directives, declarations, scriptlets and expressions
• Describe JSP interaction with HTML, servlets and other JSP pages
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v 5.0 API Specifications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-1
Instructor Guide
Figure 9-1. Unit objectives RD8107.5
Notes:
2
Unit objectivesAfter completing this unit, you should be able to:� Write JSP pages using the core JSP syntax� Directives� Declarations� Scriptlets� Expressions� Describe the general content of a JSP page� Describe how to generate XML from a JSP document� Identify the XML syntax for JSP directives, declarations,
scriptlets and expressions� Describe JSP interaction with HTML, servlets and other JSP
pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP 2.1 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-3
Instructor Guide
Figure 9-2. JSP 2.0 Specification RD8107.5
Notes:
3
JSP 2.1 specification� Java Server Pages 2.1 provides two syntax types for JSP files:
�JSP Page syntax�JSP Document (XML) syntax
� JSP Page syntax is discussed in this presentation. JSP Document syntax is discussed later.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Syntax Elements
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-5
Instructor Guide
Figure 9-3. JSP Syntax Elements RD8107.5
Notes:
JSP directives are messages for the JSP engine. They do not directly produce any visible output, but tell the engine what to do with the rest of the JSP page.
JSP declarations let you define page-level variables to save information or define supporting methods that the rest of a JSP page may need.
JSP expressions are evaluated at runtime, and the results are converted to a string and directly included within the output page. Typically expressions are used to display simple values of variables or return values by invoking a bean's getter methods.
JSP scriptlets are run when the request is serviced by the JSP page. Almost any valid Java code can appear within a scriptlet.
JSP actions include various kinds of JavaBean access and custom tags, and aim to extend HTML or XML syntax with macros that actually result in Java method invocations.
4
JSP syntax elements� JSP elements fall into four groups:
�Directives�Scripting
� Declarations� Expressions� Scriptlets
�Comments�Actions
� Directives and scripting have both non-XML syntax and XML syntax
� Actions are only written in XML syntax
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Directives
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-7
Instructor Guide
Figure 9-4. JSP Directives RD8107.5
Notes:
Directives are used to provide instructions to the JSP engine itself, that is, its run-time or operational parameters. There are three different JSP directives: page, include, and taglib.
5
JSP directives� JSP directives are instructions processed by the JSP engine
when the page is compiled into a servlet<%@ directive {attribute="value"}* %>
� JSP technology currently defines page, include, and taglib directives
<%@ page language="java" %>
<%@ include file="companyBanner.html"%>
<%@ taglib uri="tagLibraryURI"
prefix="tagPrefix" %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — The “*” in the syntax means that multiple instances are allowed.
Transition statement — Next: The JSP Page Directive
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-9
Instructor Guide
Figure 9-5. The JSP Page Directive RD8107.5
Notes:
The * in the syntax indicates that more than one attribute may appear. Attributes are separated with white space.
The isThreadSafe directive is not listed here, since, though not deprecated itself, it may result in deprecated servlet code.
6
The JSP page directive� Defines page-specific attributes
�Apply to complete translation unit� Syntax:
<%@ page attribute* %>
where attributes may include any of:language=“scriptingLanguage”extends=“className”
import=“importList”
session=“true|false”
buffer=“none|sizekb”
autoFlush=“true|false”
info=“info_text”
isErrorPage=“true|false”
contentType=“ctinfo”
pageEncoding=“peinfo”
isELIgnored=“true|false”
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Some of the more commonly used directives are explained in further detail in the next several slides.
Transition statement — Next: JSP Page Directives - import
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-11
Instructor Guide
Figure 9-6. JSP Page Directives - import RD8107.5
Notes:
7
JSP page directives: import� Comma-separated list of Java language package names or
class names that the servlet imports� Can be specified multiple times within a JSP file to import
different packages
<%@ page import ="java.io.*,java.util.Hashtable" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Page Directives - session
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-13
Instructor Guide
Figure 9-7. JSP Page Directives - session RD8107.5
Notes:
The default value for session is true, which means the JSP is session-aware and accesses/creates the current HttpSession.
8
JSP page directives: session� session
�If true, this page participates in an HTTP session. The implicit script variable session (of type javax.servlet.http.HttpSession) is the session for the page
�If false, the session variable is not available and any reference to it results in a fatal translation error
�Defaults to true
<%@ page session="true" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Page Directives - buffer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-15
Instructor Guide
Figure 9-8. JSP Page Directives - buffer RD8107.5
Notes:
9
JSP page directives: buffer� buffer
�Specifies the buffering mode for the out JspWriter�If buffer="none", there is no buffering, and all of the
output is written directly to the ServletResponse object's PrintWriter
�If a buffer size is provided, all output is written to a buffer with a size not less than the specified value
�If no buffer parameter is specified, the default is a buffered JspWriter with a buffer size not less than 8 KB
�See also autoFlush
<%@ page buffer="12kb" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — The actual buffer minimum is up to the developer of the particular JSP compiler, but it must not be less than 8 KB.
Transition statement — Next: JSP Page Directives - autoFlush
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-17
Instructor Guide
Figure 9-9. JSP Page Directives - autoFlush RD8107.5
Notes:
10
JSP page directives: autoFlush� autoFlush
�For buffered output�If true, the output is flushed automatically when the buffer
is full�If false, an exception is thrown if the buffer is full�It is illegal to specify autoFlush="false" when buffer="none"
�Defaults to true
<%@ page autoFlush="true" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Setting autoFlush=”false” is one way to cause a runaway JSP (a page producing more HTML than expected) to fail.
Transition statement — Next: JSP Page Directives - isErrorPage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-19
Instructor Guide
Figure 9-10. JSP Page Directives - isErrorPage RD8107.5
Notes:
isErrorPage is false by default. If true, the implicit script variable exception is defined and the entire servlet logic is surrounded by a try-catch block.
11
JSP page directives: isErrorPage� isErrorPage
�Indicates that the JSP page is intended as the URL target of another JSP page's errorPage
�If true, the variable exception is defined, and is a reference to the Throwable object of the JSP page in error
�Defaults to false
<%@ page isErrorPage="true" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Page Directives - errorPage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-21
Instructor Guide
Figure 9-11. JSP Page Directives - errorPage RD8107.5
Notes:
The errorPage defines a URL to which an uncaught exception is forwarded.
12
JSP page directives: errorPage� errorPage
�Defines a URL to a JSP page that is invoked if a throwable object is thrown but not caught by this JSP
�The default URL is implementation-dependent
<%@ page errorPage="/oops.jsp" ... %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Page Directives - contentType
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-23
Instructor Guide
Figure 9-12. JSP Page Directives - contentType RD8107.5
Notes:
The main requirement for generating XML is that the JSP page set the content type of the page appropriately:
<%@ page contentType=”text/xml”%>
13
JSP page directives: contentType� contentType
�The MIME type of the generated response. This information is used to generate the response header. You can optionally use this directive to specify the character set in which the page is to be encoded.
�Syntax: � contentType="TYPE"
OR� contentType="TYPE;charset=CHARSET"
�Default values for TYPE= "text/html" and CHARSET="ISO-8859-1"
<%@ page contentType = "text/html" ...%>
OR<%@ page contentType =
"text/html;charset=iso-8859-1" ...%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The <%@ include %> and <%@ taglib %> Directives
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-25
Instructor Guide
Figure 9-13. The <%@ include %> and <%@ taglib %> Directives RD8107.5
Notes:
This allows reusable .html and .jsp to be composed at translation time (when the JSP is compiled). The implication of translation time is that a single page is generated prior to code generation. Such included content should not be subject to change, as such change will not be picked up (at run time) by the JSP.
This contrasts with the <jsp:include> and <jsp:forward> actions presented later.
14
The <%@ include %> and <%@ taglib %> directives� Include is used to substitute text or code at translation
(compile) time
<%@ include file="relativeURLspec" %>
� Taglib is used to declare a tag library containing custom tags
<%@ taglib uri="tagLibraryURI“prefix="tagPrefix"%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Scripting (1 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-27
Instructor Guide
Figure 9-14. JSP Scripting (1 of 4) RD8107.5
Notes:
Scripting provides the bulk of the JSP code.
Scriptlets are Java code fragments that are directly placed in the body of the generated method.
The order of appearance (of the scriptlets) within the .jsp is maintained by Page Compilation.
Frequently, the result of scriptlet execution is the addition of text (Java String) to the JspWriter.
JSP Expression syntax is a shortcut for this typical case. Note, there is no ‘;' in a JSP expression.
15
JSP scripting (1 of 4)� Declarations
�Used to declare instance and class variables and methods in the scripting language used in a JSP page
<%! declaration %>
<%!
private int getDateCount =0;
private String getDate
(GregorianCalendar gc1)
{...method body here...}
%>
�jspInit and jspDestroy methods may be defined here
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Scripting (2 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-29
Instructor Guide
Figure 9-15. JSP Scripting (2 of 4) RD8107.5
Notes:
Scriptlets are blocks of Java code embedded in a JSP page.
16
JSP scripting (2 of 4)� Scriptlets (inline Java code)
�Java code makes up the body of the generated method
<% valid_code_fragment %>
<%if(Calendar.getInstance().
get(Calendar.AM_PM)==Calendar.AM){%>
How are you this morning?
<%}else{%>
How are you this afternoon?
<%}%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Scripting (3 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-31
Instructor Guide
Figure 9-16. JSP Scripting (3 of 4) RD8107.5
Notes:
17
JSP scripting (3 of 4)� Comments
�Similar to HTML comments�Stripped from the page by the JSP engine when
executed
<%-- comment --%>
<%-- check for AM or PM --%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Scripting (4 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-33
Instructor Guide
Figure 9-17. JSP Scripting (4 of 4) RD8107.5
Notes:
18
JSP scripting (4 of 4)� Expressions
�The expression is evaluated�Result is converted to a String and displayed
<%= expression %>
�The following example calls the incrementCountermethod declared in the declarations block, and prints the result
<%=incrementCounter()%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Variables
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-35
Instructor Guide
Figure 9-18. Variables RD8107.5
Notes:
19
Variables� Within both Scriptlets and Expressions, there are certain
implicit objects available for use (without being declared first)� Implicitly defined variables available for scripting:
�request: HttpServletRequest object�response: HttpServletResponse object�pageContext: the PageContext for this JSP page�session: HttpSession object (if any)�application: the ServletContext object�config: ServletConfig object for this JSP page�out: JspWriter�page: the JSP page's implementation class processing the
current request (for Java, page is a synonym for this)�exception: the throwable object passed to this error page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Scope Factors
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-37
Instructor Guide
Figure 9-19. Scope Factors RD8107.5
Notes:
20
Scope Type Variable Factor
page PageContext pageContextUsed internally by the page compiler, and by custom tag libraries.
request ServletRequest request
Information relevant to a specific user for a specific HTTP request/response pair.
session HttpSession session
Information relevant to a specific user for a series of request/response pairs.
application ServletContext application
Information specific to a group of users across multiple servlets in a Web application.
Scope factors
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Exception Handling
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-39
Instructor Guide
Figure 9-20. Exception Handling RD8107.5
Notes:
21
Exception handling� You can provide your own exception handling within JSP
pages�It may not be possible to anticipate all situations
� Use the page directive's errorPage attribute�Forward an uncaught exception to an error handling JSP
page for processing.
<%@ page isErrorPage="false"
errorPage="errorHandler.jsp" %>
�flag errorHandler.jsp as an error processing page:
<%@ page isErrorPage="true" %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The Include and Forward Actions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-41
Instructor Guide
Figure 9-21. The Include and Forward Actions RD8107.5
Notes:
The include and forward actions represent direct calls to a RequestDispatcher's include or forward method, respectively. The page attribute for each of these actions is passed as an argument to the getRequestDispatcher method call on the ServletContext. Note that the include action is performing a run-time include of the named resource. Thus, if the resource content changes, that change is reflected in any jsp:include calls performed after the change. No page-level context is shared between the dispatching and dispatched JSPs.
The flush = “true” parameter is required with JSP 1.1.
22
The include and forward actions� Interact with the RequestDispatcher mechanism
� Include<jsp:include page="StdHeader.jsp" flush="true" />
�Execution of current page continues after including response from target
� Forward<jsp:forward page="ExtraInfo.jsp" />
�Execution of current page is terminated and target resource has full control over request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Interactions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-43
Instructor Guide
Figure 9-22. JSP Interactions RD8107.5
Notes:
In general, JSPs are invoked to present a response to a request.
23
JSP interactions� You can invoke a JSP page:
�By the URL�By a servlet�By another JSP page
� A JSP page can invoke:�A servlet�Another JSP page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Invoking a JSP by URL
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-45
Instructor Guide
Figure 9-23. Invoking a JSP by URL RD8107.5
Notes:
24
Invoking a JSP by URL� You can invoke a JSP page by URL
�From within the <FORM> tag of a JSP or HTML page�From another JSP page
� To invoke a JSP page by URL, use the following syntax:
http://servername/path/filename.jsp
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Calling a JSP page from a Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-47
Instructor Guide
Figure 9-24. Calling a JSP Page from a Servlet RD8107.5
Notes:
25
Calling a JSP page from a servlet� You can call JSP pages using the same RequestDispatcher interface that you use to call servlets from servlets
getServletContext().
getRequestDispatcher
("/pages/showResults.jsp").
forward(req, res);
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:The instructor may want to have the students act out the roles of the servlet, request dispatcher and JSP. This changes the pace and helps illustrate how a servlet calls a JSP.
Purpose —
Details —
Additional information — If the buffer is flushed, and the forward() is executed, an exception is thrown. The forward() flushes the buffer.
Transition statement — Next: Invoking a Servlet from a JSP Page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-49
Instructor Guide
Figure 9-25. Invoking a Servlet from a JSP Page RD8107.5
Notes:
26
Invoking a servlet from a JSP page� You can invoke a servlet from a JSP page, either as an action
on a form or directly through the jsp:include or jsp:forward tags.�To invoke a servlet within the HTML <FORM> tag, the
syntax is as follows :
<FORM METHOD="POST|GET"
ACTION="application_URI /Servlet_URL ">
<!--Other tags such as
text boxes and buttons go here-->
</FORM>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Invoking a JSP page from another JSP page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-51
Instructor Guide
Figure 9-26. Invoking a JSP Page from Another JSP Page RD8107.5
Notes:
27
Invoking a JSP page from another JSP page� To invoke a JSP file from another JSP file, you can:
�Specify the URL of the second JSP file on the form action attribute:
<form action="/MYAPP/DateDisplay.jsp">
�Specify the URL of the second JSP file in an anchor tag href attribute:
<a href="/MYAPP/InfoDisplay.jsp">
reference-text </a>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Scripting Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-53
Instructor Guide
Figure 9-27. Scripting Example RD8107.5
Notes:
The above code represents a sample JSP file. Here you should note that a scriptlet pulls in an object from the request object. Also notice that a <TABLE> is generated and filled in with the contents of the object retrieved from the request object.
28
Scripting example<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD><TITLE></TITLE></HEAD>
<BODY>
<%TestAreas tests=
(TestAreas)request.getAttribute("tests");%>
<TABLE cellspacing="10"><TBODY>
<TR>
<TD><FONT color="#0000cc" size="5" face="Comic Sans MS">The following areas have tests available</FONT></TD>
</TR>
<%for (int i = 0; i < tests.getTestAreas().length; i++){%>
<TR><TD align="center">
<!-- The following two lines are really 1 line -->
<A href="/Course/ExamCommand?cmd=displayTestsByArea&testArea=
<%= tests.getTestAreas(i).getKey()%>">
<IMG border="0"
src="<%= tests.getTestAreas(i).getImageFileWithPath() %>"></A>
</TD></TR>
<%}%>
</TBODY> </TABLE> </BODY>
Scripting is possible (but not encouraged) in JSP
pages. It will be replaced in subsequent
modules.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Scripting Example Output
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-55
Instructor Guide
Figure 9-28. Scripting Example Output RD8107.5
Notes:
This is part of the page generated by the previous .jsp file as viewed by the browser. Note the three test areas displayed in the table.
29
Scripting example output
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-56 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Actions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-57
Instructor Guide
Figure 9-29. JSP Actions RD8107.5
Notes:
The final group of JSP elements consists of Actions. The JSP specification defines a number of standard Actions. The specification also requires support for an arbitrary number of Custom actions that are defined via classes specified in a taglib directive.
You looked at the jsp:include and jsp:forward actions earlier. Discussions of the other standard Actions are deferred until a subsequent module.
The plug-in action allows you to provide the attributes necessary to create and send the appropriate Object or Embed tag back to the browser requesting that code be run via the appropriate Java plug-in.
Note
Custom actions are discussed in a subsequent module.
30
JSP actions� Actions perform a variety of functions, and extend the
capabilities of JSP�Standard
� <jsp:useBean>
� <jsp:setProperty>
� <jsp:getProperty>
� <jsp:include>
� <jsp:forward>
� <jsp:param>
� <jsp:plugin>
– <jsp:params>
– <jsp:fallback>
�Custom� Introduced via the taglib directive
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-58 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Document Syntax
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-59
Instructor Guide
Figure 9-30. JSP Document Syntax RD8107.5
Notes:
31
JSP document syntax� JSP document (XML) syntax provides the same functionality
as JSP page syntax with added benefits:�JSP documents can be manipulated by XML-aware tools�The XML view of a JSP document can be used to validate
the document�A JSP document can be generated from a textual
representation by applying an XML transformation� JSP documents are namespace-aware XML documents
�XML namespaces identify the core syntax� The JSP document and JSP page syntax cannot be mixed in
one file� A JSP file in one syntax can include or forward to a file in the
other syntax
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-60 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: XML Tags (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-61
Instructor Guide
Figure 9-31. XML Tags (1 of 2) RD8107.5
Notes:
In an XML document there can only be one root (or outermost) tag. When using the XML syntax for the JSP tags, you can use the <jsp:root> tag as the document's root tag. For example:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
...
<jsp:expression>new Date()</jsp:expression>
...
<jsp:expression>aCust.getName()</jsp:expression>
...
</jsp:root>
32
XML tags (1 of 2)� The JSP specification provides special tags for XML
documents:�XML Document root tag
<jsp:root
xmlns:jsp="http://java.sun.com/JSP/Page"version="2.0">
...
</jsp:root>
�Directives<jsp:directive.directive { attr=”value” }* />
Declarations
<jsp:declaration>
...
</jsp:declaration>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-62 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: XML Tags (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-63
Instructor Guide
Figure 9-32. XML Tags (2 of 2) RD8107.5
Notes:
33
XML tags (2 of 2)� Scriptlet
<jsp:scriptlet>
code fragment goes here
</jsp:scriptlet>
� Expressions<jsp:expression>
expression goes here
</jsp:expression>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-64 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Document versus Page Syntax (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-65
Instructor Guide
Figure 9-33. Document versus Page Syntax (1 of 2) RD8107.5
Notes:
34
Document versus page syntax (1 of 2)
XML JSP Syntax Traditional JSP Syntax<jsp:root xmlns:jsp=”dtd”>
remainder of JSP page</jsp:root>
None
<jsp:directive.include file="copyright.html" />
<%@ include file="copyright.html" %>
<jsp:declaration>private int getDateCount =0;private String getDate
(GregorianCalendar gc1){...method body here...}</jsp:declaration>
<%!private int getDateCount =0;private String getDate
(GregorianCalendar gc1){...method body here...}%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-66 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Document versus Page Syntax (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-67
Instructor Guide
Figure 9-34. Document versus Page Syntax (2 of 2) RD8107.5
Notes:
35
Document versus page syntax (2 of 2)
XML JSP Syntax Traditional JSP SyntaxHow are you this<jsp:scriptlet>if (isAM) {
out.print(" morning?");} else {
out.print(" afternoon?");}</jsp:scriptlet>
How are you this<%if (isAM) {
out.print(" morning?");} else {
out.print(" afternoon?"); }%>
<jsp:expression>customer.getFirstName()</jsp:expression>
<%= customer.getFirstName() %>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-68 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Issues
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-69
Instructor Guide
Figure 9-35. JSP Issues RD8107.5
Notes:
With the scripting subset of JSP, the tendency might be to place lots of Java code within this Template page. Don't fall into that trap!
36
JSP issues� Advantages:
�Can build and maintain presentation using page authoring tools
�Full support for Java on the server-side
� Disadvantages:�Excessive Java code pollutes HTML�Poor separation of responsibility �(.jsp owned by both Page Designer
and Logic Developer)
Addressed by use of JavaBeans and custom tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-70 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-71
Instructor Guide
Figure 9-36. Checkpoint RD8107.5
Notes:
Write down your answers here:
37
Checkpoint1. What is a JSP page composed of?2. What executes when a JSP page is invoked?3. Which JSP scripting statement does not allow a closing
semicolon?4. Why is the <jsp:root> tag needed?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-72 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
38
Checkpoint solutions1. A JSP page is composed of standard HTML tags and JSP-
specific tags.2. When a JSP page is invoked, either by a direct request
from a browser or a call from a servlet, it is compiled into a servlet by the Web container. If the generated servlet already exists, and is newer than the associated JSP source, the compile will not repeat.
3. An expression does not include a typical closing semicolon within the enclosing tag.
4. In an XML document there can only be one root (or outermost) tag. When using the XML syntax for the JSP tags, you can use the <jsp:root> tag as the document’s root tag.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-73
Instructor Guide
Figure 9-37. Unit summary RD8107.5
Notes:
39
Unit summaryHaving completed this unit, you are able to:� Write JSP pages using the core JSP syntax
�Directives�Declarations�Scriptlets�Expressions
� Describe the general content of a JSP page� Discuss how to generate XML from a JSP page� Identify the XML syntax for JSP directives, declarations,
scriptlets, and expressions� Explain JSP interaction with HTML, servlets, and other JSP
pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-74 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 9. JavaServer Pages Specification and Syntax 9-75
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
9-76 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 10. Page Designer in Application Developer for JSP DevelopmentEstimated time
00:30
What this unit is about
This unit describes the Page development tool, Page Designer, that is integrated with Rational Application Developer. It describes the features of Page Designer for building JavaServer Pages (JSP) artifacts.
What you should be able to do
After completing this unit, you should be able to:
• Explain the IBM Rational Application Developer tooling used for developing and testing JavaServer Pages (JSP) artifacts
• Explain the functions of the Rational Application Developer Page Designer
• Identify the different Page Designer views
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://publib.boulder.ibm.com/infocenter/radhelp/v7r5/index.jsp IBM Rational Application Developer V7.5.2 Help
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-1
Instructor Guide
Figure 10-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Explain the IBM Rational Application Developer tooling used for developing and testing JSP artifacts
�Describe the functions of the Rational Application Developer's Page Designer tool
�Identify the different Page Designer views
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Page Designer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-3
Instructor Guide
Figure 10-2. Page Designer RD8107.5
Notes:
3
Page designer� Rational Application Developer ships with a page editor and
designer: Page Designer� Page Designer includes the following basic functions:
�Page composition and editing�Image map editor�Dynamic HTML�Cascading Style Sheets�JSP development�JavaScript development
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Page Designer Views
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-5
Instructor Guide
Figure 10-3. Page Designer Views RD8107.5
Notes:
The main editor presents three different views to the developer. They are shown in the next three foils.
4
Page designer views� Page Designer has different tabs and views for editing HTML
and JSP pages:�Design: drag-and-drop HTML design�Source: directly edit source code�Preview: refer to the page in a browser�Split: displays design and preview simultaneously�Outline: navigation via HTML tags�Properties: guided editing of HTML attributes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Page Editing
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-7
Instructor Guide
Figure 10-4. Page Editing RD8107.5
Notes:
Design view -- this view provides WYSIWYG editing. Drag and drop files, images, and audio files onto the page. Work with graphic layout aids. Make use of property sheets (shown later in this unit) to set HTML tag attributes.
This is the main view for creating and editing documents.
5
Page editing in the Design view�
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: HTML Source
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-9
Instructor Guide
Figure 10-5. HTML Source RD8107.5
Notes:
Source view -- This is the view which shows and allows edits to the raw HTML text.
The Outline View is a good companion to the source view. This shows the nesting of the HTML tags within the document. If it is not in your perspective, get it by selecting menu item Window ?Show View ?Outline.
Navigation is usually easiest by selecting an object in Design mode and then switching to the source mode.
Code assist is available for both HTML and JSP tags.
6
HTML code in the Source view
�
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Preview
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-11
Instructor Guide
Figure 10-6. Preview RD8107.5
Notes:
Preview mode -- Run the page inside an Internet Explorer browser instance. Note that server-side code, such as JSP expressions, cannot be previewed.
7
Preview
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Rich HTML Editor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-13
Instructor Guide
Figure 10-7. Rich HTML Editor RD8107.5
Notes:
There is a rich menu of controls to compose and edit pages with both static and dynamic content. The Palette and Snippets views provide similar features through drag and drop capability. Assistance with Frames, Cascading Style Sheets (CSS), Tables, Forms, and more is provided.
8
Rich HTML editor� Normal list shows palette with details for JSP Tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Editing HTML and JSP Tag Attributes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-15
Instructor Guide
Figure 10-8. Editing HTML and JSP Tag Attributes RD8107.5
Notes:
HTML and JSP tags support attributes for passing parameters to the interpreter. The way to populate HTML tag attributes from the Design view is to bring up the Properties dialog for the that tag.
In the example above, the patron field has been selected in the Design view. The Properties view shows the various attributes of the HTML INPUT tag, with the values currently set for the patron field.
By default only the most used attributes are shown. Click the All Attributes button in the Properties view toolbar to display all the information for an element.
9
Editing HTML and JSP tag attributes� The Properties view provides a convenient editor for HTML tag
attributes� You can select elements in three ways:
�From the Design or Outline view, by clicking the element�From the Source view, by placing the cursor within the text
for the element� Navigate the hierarchical structure on the left to change
attributes of enclosing or enclosed elements
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — The Propertiesview replaces the Attributesview in Rational Application Developer . WebSphere Studio Application Developer also had a Propertiesview, but its interface has changed and its use has been expanded.
Transition statement — Next: JSP Expressions, Scriptlets, and Declarations
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-17
Instructor Guide
Figure 10-9. JSP Expressions, Scriptlets, and Declarations RD8107.5
Notes:
Page Designer supplies a number of ways of entering JSP tags into the document.
10
JSP expressions, scriptlets, and declarations� You can use the JSP menu to add standard JSP tags, with
choices including Insert Expression, Insert Scriptlet, and so on.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Note that the objects (library, methods, and properties) can be dragged into the edit window. The corresponding code then appears as source.
Transition statement — Next: Custom Tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-19
Instructor Guide
Figure 10-10. Custom Tags RD8107.5
Notes:
11
Custom tags� The JSP > Insert Custom menu item provides support for
custom JSP tags, via a list that shows the tags in a tag library
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Web Project JSP Validator
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-21
Instructor Guide
Figure 10-11. Web Project JSP Validator RD8107.5
Notes:
When a JSP file is saved, it is compiled, and like a .java file, compile error messages appear in the Problems list.
Validating the project revalidates all of the JSP files in the project.
The JSP Validator uses the Web project's buildpath to invoke JSP Page Compilation. Any resulting syntax or compilation error messages are logged in the Problems list.
Additionally, Application Developer also has an HTML validator for Web projects which checks HTML syntax. You can also check syntax at any time from the Application Developer main menu by selecting Tools Validate HTML Syntax. Page Designer lists any tags that are syntactically incorrect. You can then click to locate them in a document and correct them yourself, or have Page Designer correct them for you.
Note that both of these validators can be turned off at the project level. To do this, right-click the project in the Project Explorer, and choose Properties ?Validation.
12
Web project JSP validator
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Running JSP Files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-23
Instructor Guide
Figure 10-12. Running JSP Files RD8107.5
Notes:
13
Running JSP files� Test JSP files by running them on a server (Run As > Run on
Server)
�
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-25
Instructor Guide
Figure 10-13. Checkpoint RD8107.5
Notes:
Write down your answers here:
14
Checkpoint1. What is the Page Designer?2. What views are available in the Page Designer?3. What support does Page Designer have for JSP pages?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
15
Checkpoint solutions� Page Designer is the built-in Web page authoring tool in
Rational Application Developer . � Page Designer presents four views to the developer:
� Design (WYSIWYG)� Source (Raw Tag Source)� Split (Design and Preview split in one view)� Preview (run in Internet Explorer)
� Page Designer has a rich set of controls to insert JSP tags from the Design view. These are accessible via the JSPand Insert menus. There is a Script editor for entering scriptlets and expressions.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-27
Instructor Guide
Figure 10-14. Unit summary RD8107.5
Notes:
16
Unit summary� Having completed this unit, you are able to:
� Explain the Rational Application Developer tooling used for developing and testing JSP artifacts
� Discuss the functions of the Rational Application Developer's Page Designer tool
� Identify the different Page Designer views
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 10. Page Designer in Application Developer for JSP 10-29
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
10-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 11. Web Application DebuggingEstimated time
00:20
What this unit is about
This unit describes the JSP debugging facilities in Rational Application Developer.
What you should be able to do
After completing this unit, you should be able to use the JSP debugging facilities available in Rational Application Developer.
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://publib.boulder.ibm.com/infocenter/radhelp/v7r5/topic/com.ibm.etools.webtoolscore.doc/topics/tdebugwebapp.html Debugging Web applications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-1
Instructor Guide
Figure 11-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Place breakpoints in a valid location inside a JSP page�Use the JSP debugger�Ask the JSP compiler to keep the generated code�Look at servlet that the JSP page was compiled into
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Debugger
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-3
Instructor Guide
Figure 11-2. Debug Perspective RD8107.5
Notes:
The debugger allows you to step through JSP source code -- not the resulting Java servlet source.
By default you see the JSP Implicit Variables, however you can also click on the Variables view toolbar and click Show All Java variables.
The debugger is running and letting you manipulate the variables of the generated servlet.
Breakpoints can be set within a JSP in the Source view of Page Designer.
3
Debug perspective
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Enabling JSP Debugging
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-5
Instructor Guide
Figure 11-3. Enabling JSP Debugging RD8107.5
Notes:
Breakpoints can be set in the JSP source view with the context menu.
With step-by-step debug mode, a dialog mode is presented at each servlet or JSP's entry. This gives the user the choice to skip the code or step into the code to start debugging. The step-by-step mode may be turned off by checking the Disable Step-by-Step Debug entry in the dialog box, through preferences, or with the Enable/Disable Step-by-Step Debugging button on the Debug view.
4
Enabling JSP debugging� The server needs to be running in Debug mode� Set a breakpoint in a JSP file (Source view of Page Designer)� Breakpoints can only be set at the following places
�<jsp:useBean/>, <jsp:getProperty/>,<jsp:setProperty/>
�<jsp:include />, <jsp:forward/>
�JSP Scriptlets�JSP Expressions�JSP Declarations
� Step-by-step debugging mode presents a dialog box at the entry of each servlet and JSP�Select Skip or Step-Into
from dialog box
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Debugging
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-7
Instructor Guide
Figure 11-4. JSP Source RD8107.5
Notes:
Here you see the Debugger. Note that the Outline view provides the document outline view of the JSP.
5
JSP source� Steps through the JSP page, not the underlying servlet� Use the Outline view to navigate to elements
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Instructors should use this slide to go through the various features and views of the debugger in detail. You may prefer to break away from the charts and go into a live demonstration at this point. If so, a solution workspace to one of the course exercises will make a good starting point.
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-9
Instructor Guide
Figure 11-5. Debug View RD8107.5
Notes:
a. Resume: resumes thread
b. Disconnect: threads resume in remote VM and the debugging session is over. Need to reconnect by right-clicking on the server in the Servers view and clicking Reconnect debug process
c. Step Into: steps into a method
d. Step Over: steps over a method
e. Step Return: step to a return statement or to the end of a method
f. Drop To Frame: drop to the selected method in the call stack
g. Use Step Filters / Step Debug: only step in the packages or classes you are interested in
h. Enable Step-by-Step mode
6
Debug view� Displays the stack trace of the generated servlet
�For example Login.jsp is compiled to _Login.java� Controls to
1.Resume2.Disconnect 3.Step Into4.Step Over5.Step Return6.Drop To Frame7.Use Step Filters
/ Step Debug8.Enable
Step-by-Step mode
1
2
7
6
5
4
3
8
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-11
Instructor Guide
Figure 11-6. Variables View RD8107.5
Notes:
7
Variables view� Displays implicit objects from JSP 2.0� You can explore and change values (right-click and select
Change Value)� Click the toolbar drop-down menu to Show All Jython
Variables or Show All Java Variables�Displays variables from the underlying servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-13
Instructor Guide
Figure 11-7. Breakpoints View RD8107.5
Notes:
8
Breakpoints view� Manages breakpoints in the workbench� Set breakpoint properties, such as Hit Count and Boolean
conditions on when to break
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-15
Instructor Guide
Figure 11-8. Keep Generated Servlet Java Source RD8107.5
Notes:
The WebSphere Extensions Editor also allows you to specify JSP Attributes such as keepgenerated and scratchdir to specify the JSP compiler to keep the generated code and where to keep the generated code.
9
Keep generated servlet Java source� By default, the JSP
compiler does not keep the Java source file of the generated servlet
� Use external tool JSP Batch Compiler from context menu Compile JSPs…�Make a note of the
compileToDirargument
� Note Login.jspbecomes _Login.java
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-17
Instructor Guide
Figure 11-9. View Generated Servlet code RD8107.5
Notes:
The _jsp_string(s) represent static html in the jsp.
JSP expressions are embedded in a print() statement.
JSP Expression Language code is passed in as a String and evaluated by the PageContextImpl instance.
10
View generated servlet code� Click File >Open File, navigate to scratchdir and Open .java filespublic void _jspService(HttpServletRequest request, HttpServletResponse response)throws … {
…
try {
out.write(_jsp_string1);
out.write(_jsp_string2);
out.write(_jsp_string3);
out.print(request.getContextPath());
out.write(_jsp_string4);
…
out.write((java.lang.String)
PageContextImpl.proprietaryEvaluate("${MESSAGE}"…);
out.write(_jsp_string6);
} catch (Throwable t)
…}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-19
Instructor Guide
Figure 11-10. Checkpoint RD8107.5
Notes:
Write down your answers here:
11
Checkpoint1. What type of code is visible in the source pane of the
debugger when you debug JSP pages?2. How can you inspect the current JspWriter stream while
debugging?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
12
Checkpoint solutions1. The source JSP (markup) file is what shows in the
debugger source edit window (not the Java servlet code). 2. To look at the buffer, look at the out variable.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-21
Instructor Guide
Figure 11-11. Unit summary RD8107.5
Notes:
13
Unit summary� Having completed this unit, you are able to:
�Place breakpoints in a valid location inside a JSP�Use the JSP debugger�Ask the JSP compiler to keep the generated code�Look at servlet that the JSP was compiled into
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 11. Web Application Debugging 11-23
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
11-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 12. Servlet API (Part II)Estimated time
01:00
What this unit is about
This unit discusses the core servlet APIs needed for the processing of headers, sharing of objects between servlets, and for forwarding requests to other servlets. These are all key parts of all servlet-based Web applications.
This unit also introduces the concept of using the servlet as a controller when using the model-view-controller design pattern.
What you should be able to do
After completing this unit, you should be able to:
• Discuss servlets as controllers
• Look at the processing or request and response headers
• Understand how servlets handle redirection
• Discuss object sharing
• Understand the requirements for special characters in HTML documents
• Discuss multithreading and thread safety issues
• Describe some of the internationalization support for servlets
• Understand the use of and need for the servlet context
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-1
Instructor Guide
Figure 12-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Discuss servlets as controllers (Model-View-Controller architecture)
�Look at the processing of request and response headers �Explain how servlets handle redirection�Discuss object sharing�Look at how servlets can forward to or include content
from other servlets �Explain the requirements for special characters in HTML
documents�Discuss multi-threading and thread safety issues�Describe some of the internationalization support for
servlets�Describe the use of and need for the servlet context
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Overview of Model-View-Controller (MVC)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-3
Instructor Guide
Figure 12-2. Overview of Model-View-Controller (MVC) RD8107.5
Notes:
In servlet-only applications, the servlet is used as both the controller and the view. Servlets process the requests (control) and produce the HTML response (view). In some cases, such as when using JDBC to access back-end data, the servlet also acts as the model.
HTML, DHTML, JavaScript, and XML are useful for the static components of the programming model, while servlets (controller) and JSP pages (view) are the most useful components in generating dynamic content. Data structure JavaBeans and business logic access Beans (model) are useful for business logic and data hosted on back-end servers. Together these components provide the basis for a very effective MVC architecture.
3
Overview of Model-View-Controller (MVC)� Servlet-only applications: servlet acts as model, view, and
controller�Poor separation of concerns
� Servlet and JSP applications: the servlet is the controller, theJSP page is responsible for presentation, and other Java classes are the model�Servlets (controller)�JSP page (view)�Business logic (model)
� JavaBeans components� Enterprise JavaBeans (EJB) components
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Model-View-Controller (MVC)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-5
Instructor Guide
Figure 12-3. Model-View-Controller (MVC) RD8107.5
Notes:
This picture is often referred to as JSP Model 2 (in Sun Microsystems's early JSP Specification documents). This is a very common design in object-oriented systems.
The typical scenario is likely to be:
1. A request is made to a Servlet.
2. The servlet, acting as a Controller, locates or creates one or more objects which will be responsible for generating and encapsulating the desired dynamic content. The objects are JavaBeans or Enterprise JavaBeans (EJBs).
3. The servlet directs the operation of these beans.
4. The servlet then selects the result View by forwarding control to a selected JSP page. The page is supplied a handle to one or more JavaBeans, from which it extracts the dynamic content. The JavaBean is generally provided to the JSP page via either the HttpSession object or the HttpServletRequest object.
4
Display Page (JSP)
Request
Response
Forward
Interaction Controller
(Servlet, JSP)
Enterprise Logic and
Data
Enterprise Servers
Third-tier PlatformsApplication Server
Browser
Model-View-Controller (MVC)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Controller Organization
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-7
Instructor Guide
Figure 12-4. Controller Organization RD8107.5
Notes:
Precondition checking verifies that the request is valid, given the state of the session and request environment. The request environment includes such things as security (authentication information).
The session state may indicate that this is an inappropriate request, for example, requesting to place an order when the shopping cart is empty (or nonexistent).
The structure (organization) of controllers is reusable, but the details are very specific to a particular request-response dialog associated with the application. Thus, you want to delegate all business behavior to other objects, JavaBeans, or EJBs.
5
Controller organization� The controller establishes the overall control flow in response
to a request� At the highest level, the controller must:
�Perform precondition checks �Delegate business tasks�Establish state management tasks
� The delegate business tasks step typically involves:�Locate appropriate business objects�Delegate computation to business objects�Based on responses, select a response agent
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Processing Request Headers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-9
Instructor Guide
Figure 12-5. Processing Request Headers RD8107.5
Notes:
The getHeader method returns a header given the name of the header. There can be multiple headers with the same name in an HTTP request. For multiple headers with the same name, getHeader returns the first or only value for the named header in the request; while the getHeaders method returns an Enumeration of String values.
6
Processing request headers� The request header is built by the Web browser, and sent to the Web
server� The servlet accesses the request header values from theHttpServletRequest object passed to the doGet or doPostmethods
� Headers supported differ based on HTTP level�HTTP 1.1 headers are a superset of HTTP 1.0 headers�Query the HTTP level via theHttpServletRequest.getProtocol method� Returns HTTP/1.1 for HTTP 1.1
� There are HttpServletRequest methods for standard headers�The getHeaders and getHeaderNames methods returnEnumeration objects, which provide access to all of the header values associated with a particular header name
�The getHeader method returns the first (or only) value for the named header
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Common Headers and HttpServletRequest Methods
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-11
Instructor Guide
Figure 12-6. Common Headers and HttpServletRequest Methods RD8107.5
Notes:
The getMethod() method returns the request method (as specified in the HTTP FORM element's METHOD attribute). The service() method you inherited from HttpServlet uses this method to determine which method to call - doGet(), doPost(), doPut(), doDelete(), and so on.
There are other headers that you can use in your servlets. Most of these would be accessed with the getHeader method. Some of them are:
Accept-Charset - which character sets the browser supports.
Accept-Encoding - a value that indicates whether the data should be encoded. Typically this can be either compress or gzip and allows for compressed documents.
Accept-Language - client preferred language - for example, es, da, fr, and so on.
7
Common headers and HttpServletRequest methods� Input data type and length
�Headers: Content-type and Content-length �Methods: getContentType and getContentLength
� Cookies�Header: Cookie�Method: getCookies
� Identification for authorization purposes�Header: Authorization�Methods: getAuthType and getRemoteUser
� Protocol�Method: getMethod
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — Just in case you get asked:
es - Spanish
da - Danish
fr - French
Additional information —
Transition statement — Next: Processing Request Headers (Example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-13
Instructor Guide
Figure 12-7. Processing Request Headers (Example) RD8107.5
Notes:
Here it is assumed that you are in the processRequest method and that the processRequest method was called from both the doGet and doPost methods. You don't really know if the request is a GET or POST unless you call the getMethod method.
8
// called by doGet and doPost methods to process request
private void processRequest(
HttpServletRequest request,
HttpServletResponse response)
throws ... {
...
// input parameters have been processed
String method = request.getMethod ();
if (method.equals("GET")) {
// special "GET" processing
String lang = request.getHeader("Accept-Language");
// lang has the client's language
// now set the status and resp. headers
// and build the output document
}
}
Processing request headers (example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Example of accessing some header values: method and accept-language.
Details —
Additional information —
Transition statement — Next: Setting the Response Headers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-15
Instructor Guide
Figure 12-8. Setting the Response Headers RD8107.5
Notes:
The setContentType() and setContentLength() methods map to the Content-Type and Content-Length headers. The addCookie() method maps to the Set-Cookie header.
There are additional headers that you can specify. Some of them are concerned with the document content (Content-Encoding and Content-Language); others are of use for cache control by the browser (Date, Expires, Last-Modified).
9
Setting the response headers� Can be set via the HttpServletResponse methods: setHeader, setDateHeader, and setIntHeader.�Some headers have their own methods: setContentType, setContentLength, addCookie and sendRedirect
� Response headers are required for some status codes:�Document-moved status codes (range 300 to 307)
require a Location header�Status code of 401 must have an associated WWW-Authenticate header
� Add additional support for your servlet.�Cache-Control (HTTP 1.1) and Pragma (HTTP 1.0):
cache options�Refresh: how soon (in seconds) the browser should ask for
an updated page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Content-Type
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-17
Instructor Guide
Figure 12-9. Content-Type RD8107.5
Notes:
The MIME format of main_type/sub_type is for any registered types. The form main_type/x-sub_type is for unregistered types.
Default value if not specified is text/plain.
For a list of the registered MIME types see:
http://www.iana.org/assignments/media-types/
For a list of common (including unregistered) types see:
http://www.ltsw.se/knbase/internet/mime.htp
10
Main type / subtype Document type
application/pdf Acrobat file (.PDF)
application/postscript PostScript file
application/vnd.lotus-notes Lotus Notes file
application/x-gzip Gzip archive
application/x-java-archive JAR file
application/zip Zip Archive
audio/x-wav Windows sound file
text/html HTML document
text/xml XML document
image/gif GIF image
Content-Type� The Content-Type header is set via the setContentType
method of the HttpServletResponse object� Specifies the Multipurpose Internet Mail Extension (MIME)
type of the returned document� Form is main_type/sub_type
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — The listed Web sites were verified April 2007.
Transition statement — Next: Response Header (Example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-19
Instructor Guide
Figure 12-10. Response Header (Example) RD8107.5
Notes:
Once again it is assumed that you are in code that is part of, or has been called by, doGet() or doPost(). The variable response is assumed to be the HttpServletResponse object passed to the doGet() or doPost().
11
// process input parms and request headers
...
// set the return value
response.setStatus(HttpServletResponse.SC_OK);
// set the document type
response.setContentType("text/html");
// turn off caching
if (request.getProtocol.equals("HTTP/1.0")) {
// HTTP 1.0
response.setHeader("Pragma","no-cache");
} else {
// HTTP 1.1 or later
response.setHeader("Cache-Control","no-cache");
}
response.setDateHeader("Expires", 0);
// build the output document
...
Response header (example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — In the example there really isn't any need to check for HTTP 1.0 or 1.1, and the application can simply set all three headers. If a browser gets a header it doesn't support, it simply ignores it.
Additional information —
Transition statement — Next: Response Redirection and Error Sending
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-21
Instructor Guide
Figure 12-11. Response Redirection and Error Sending RD8107.5
Notes:
You can send a temporary redirect response to a client to redirect to another Web resource. The method response.sendRedirect(“myHtml.html”) specifies the HTML page as the redirect response.
Method response.sendError(HttpServletResponse.SC_NO_CONTENT): an error code is sent as a parameter of the method. The error numbers are predefined constants of the response. The defined error page is displayed with the appropriate error message.
12
Response redirection and error sending� Response redirect: sendRedirect()
�Sends redirection response to client �URL specifies the redirection location
� May be absolute or relative� Error Sending: sendError()
�Sets a response status code�Server-specific error page describing the error sent as
response�Custom pages may be defined for specific codes in Web
deployment descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Redirection and Send Error (Example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-23
Instructor Guide
Figure 12-12. Redirection and Send Error (Example) RD8107.5
Notes:
You can assume that processRequest() was called from doGet() and doPost().
Notice that you have discovered that the current request needs to be redirected to another resource (URL). This redirect must come before any output is sent back to the client.
If the variable test contains Error, you ask the Web server to send its error page for status code 400 (bad request).
Otherwise you are redirecting the browser to a new URL (YourResults.html). Note that all URLs being used with a sendRedirect should be passed through the encodeRedirectURL method. This is required to properly handle session management.
13
private void processRequest(
HttpServletRequest request,
HttpServletResponse response) ... {
// process request headers & query data
...
// redirect to another URL
String url = "/YourResults.html";
if (test.equals("Error"))
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
else
response.sendRedirect
(response.encodeRedirectURL(url));
return;
}
Redirection and send error (example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Session management will be covered in a later unit.
Transition statement — Next: Request Dispatcher
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-25
Instructor Guide
Figure 12-13. Request Dispatcher RD8107.5
Notes:
It is common to want to have different middle-tier services invoke each other, for example, have a Servlet invoke a JSP page to handle the response processing for a request. The interface by which this is done is the RequestDispatcher interface. A RequestDispatcher is obtained for a given resource (specified by URI). There are then two interaction models or methods available to the caller, forwarding and including.
14
Request dispatcher� The RequestDispatcher allows you to forward a request
to another servlet, or to include the output from another servlet
� Used to support both forwarding processing to, and including response from, a variety of local Web resources�For example, JSP pages and HTML files
� If a reference to the RequestDispatcher is acquired from the ServletContext�Path information is relative to the ServletContext
� If a reference to the RequestDispatcher is acquired from the HttpServletRequest�Path information is relative to the path of the current
request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Request Dispatcher Flow
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-27
Instructor Guide
Figure 12-14. Request Dispatcher Flow RD8107.5
Notes:
During the handling of a request, a servlet may wish to:
• Incorporate the result of another servlet into the output stream (include).
• Delegate the continued handling of the request to another servlet (forward).
A RequestDispatcher is obtained via:
getServletContext().getRequestDispatcher(“path_to_resource”);
Path is a relative URI (relative to ServletContext's root).
Forward: Servlet A should not write to the response stream BODY, but it can set headers and the status code. Also, the request object is changed to reflect Servlet B as being the target of the request. The diagram illustrates the flow of the response, showing how Servlet B is delegated the responsibility of generating the response body. When Servlet B completes, the web container sends, commits, and closes the response stream, and the execution continues in Servlet A after the forward() statement that specified Servlet B as the target.
15
ServletA
ServletB
Content returned to browser
forward
Content returned to browser
include
Request dispatcher flow
ServletA
ServletB
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Include: Servlet B should not write any HTTP headers. Here the request object is not altered. It may include static resources, for example, HTML files. Servlet B's content is included in the current response. Servlet A may generate response content before or after Servlet B's include (or both before and after) or, possibly, include multiple servlets.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Sample Use of Request Dispatcher
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-15. Sample Use of Request Dispatcher RD8107.5
Notes:
16
Sample use of request dispatcher� Forward to a JSP page
getServletContext().
getRequestDispatcher("/pages/showBalance.jsp").
forward(request, response);
� Include static HTML
getServletContext().
getRequestDispatcher("/pages/navigation_bar.html").
include(request, response);
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Involving other Resources: Forwarding
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-16. Involving other Resources: Forwarding RD8107.5
Notes:
The resource can be a servlet, JSP file, or HTML file.
One advantage that the forward provides over the sendRedirect is that the request object of the sender is passed to the receiver. You see later that you can use this to send objects to the servlet or JSP page you are forwarding to.
17
Involving other resources: forwarding� To have another resource build the response, use the
RequestDispatcher's forward method� getRequestDispatcher(resourceName).
forward(request,response)
� IllegalStateException is thrown if the source servlet accesses the ServletOutputStream or PrintWriterobject
Request Dispatcher
showBalance.jsp
getServletContext().getRequestDispatcher("/pages/showBalance.jsp")
.forward(request, response);
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Forward Method (Example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-17. Forward Method (Example) RD8107.5
Notes:
18
private void processRequest(
HttpServletRequest request,
HttpServletResponse response) ... {
// process request headers & query data
...
// Forward the request
if (errorFound) {
String res = "/ErrorFound.html";
getServletContext().getRequestDispatcher(res).
forward(request, response);
return;
}
}
Forward method (example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-35
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Involving other Resources: Including
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-18. Involving other Resources: Including RD8107.5
Notes:
The resource can be a servlet, JSP file, or HTML file.
19
Involving other resources: including� To have another resource included in the response, use the
RequestDispatcher's include method
getRequestDispatcher(resourceName).include(request,response)
� The target resource should not set the response headers. If attempted, there is no guarantee that the target values will be used
nav_bar.html
getServletContext().getRequestDispatcher("/pages/nav_bar.html").include(req, res); Request
Dispatcher
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-37
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Include Method (Example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-19. Include Method (Example) RD8107.5
Notes:
20
private void processRequest(
HttpServletRequest request,
HttpServletResponse response) ... {
// process request headers & query data
...
// include the request
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><BODY>Start of INCLUDED request");
out.println("<P>Hi " + request.getParameter("name"));
out.flush();
getServletContext().getRequestDispatcher(
"/ILSCS01/DispatcherInclude").
include(request, response);
out.println("<P>End of request</BODY></HTML>");}
Include method (example)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-39
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Sharing Objects
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-20. Sharing Objects RD8107.5
Notes:
The ServletContext approach is useful when a group of servlets needs to work with the same object. The servlet that wants to share the object calls the ServletContext method setAttribute and specifies the objectName to be used as a key and a reference to the object. Any other servlet within that ServletContext that wants a reference to the shared object can get to it via the getAttribute method of the ServletContext (and has to use the same objectName used by the original servlet).
The ServletRequest approach is useful when doing a forward or an include, and you want to share objects between the servlets. The servlet that wants to share the object calls the HttpServletRequest object's setAttribute method. The servlet forwarded to or included calls the request's getAttribute method to get a reference to the shared object.
21
Sharing objects� There are several ways to share objects between servlets and
JSP pages:�ServletContext
getServletContext().setAttribute("objectName",anObject);
getServletContext().getAttribute("objectName");
�HttpServletRequest
request.setAttribute("objectName",anObject);
request.getAttribute("objectName");
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-41
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — The HttpSession object can also be used for sharing objects. HttpSession will be covered later.
Transition statement — Next: Sharing Objects Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-21. Sharing Objects Example RD8107.5
Notes:
The ServletContext approach is useful when a group of servlets needs to work with the same object. The servlet that wants to share the object calls the ServletContext method setAttribute and specifies the objectName to be used as a key and a reference to the object. Any other servlet within that ServletContext that wants a reference to the shared object can get to it via the getAttribute method of the ServletContext (and has to use the same objectName used by the original servlet).
The ServletRequest approach is useful when doing a forward or an include, and you want to share objects between the servlets. The servlet that wants to share the object calls the HttpServletRequest object's setAttribute method. The servlet forwarded to or included calls the request's getAttribute method to get a reference to the shared object.
22
HttpServletRequest
"CUSTOMER"Customer
Sharing objects example// Servlet "A"public void doGet (HttpServletRequest request, HttpServletResponse resp)... {
// process request headers & query dataCustomer cust;...request.setAttribute("CUSTOMER", cust);String res = "/Internal/ServletB";getServletContext().getRequestDispatcher(res).forward(request, resp);
}
// Servlet "B"public void doGet (HttpServletRequest req, HttpServletResponse resp) ... {
Customer aCust = (Customer) req.getAttribute("CUSTOMER");...}
getAttribute()
1
2
setAttribute()
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-43
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — The HttpSession object can also be used for sharing objects. HttpSession will be covered later.
Transition statement — Next: Sharing Objects Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-22. Servlet Context RD8107.5
Notes:
The ServletContext is an important object of the servlet run time available to all Servlets and JSPs. A ServletContext manages a group of cooperating servlets and JSPs (a Web application). It has an instance of a private class loader to isolate the class files it uses from all others in the JVM.
The ServletContext provides the scope for class reloading for related servlets. There is one ServletContext per Web application per JVM. Since a ServletContext manages a group of cooperating servlets and JSPs, these objects can share configuration and environment data via the ServletContext itself. The ServletContext has the setAttribute and getAttribute methods to provide this service.
getServletContext().setAttribute("home_dir", "c:\ourhome");
String homedir = (String)getServletContext().getAttribute ("home_dir");
The ServletContext also provides access to physical resources in a platform independent fashion. It returns a URL to the resource mapped to the relative path.
23
Servlet context� A Servlet Context defines a group of related servlets
�Allows for relative paths�Rooted at a particular point in the URI namespace�Scope for data sharing among servlets
� Programmatically accessed via javax.servlet.ServletContext
� Servlet Context Attributes�Allows for simple application scoped data sharing between
servlets�getAttribute and setAttribute methods
� ServletContext.getResource
�Allows a servlet to load resources specified via a relative path, without assuming an absolute directory structure on the server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-45
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Containers and Servlet Context
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-23. Web Containers and Servlet Context RD8107.5
Notes:
Note that the URL namespace is partitioned around the ServletContext. A ServletContext in WebSphere Application Server is associated with a Web Application (Web application). Each of these share a name in the URL namespace. All servlets and JSPs which are part of ServletContext share its URL as a prefix for their URL.
For example, consider a ServletContext which is identified by the root URI www.hotel.ibm.com/Rooms and the two servlets shown. Associated with this servlet context are www.hotel.ibm.com/Rooms/Login and www.hotel.ibm.com/Rooms/DisplayRooms. These two servlets, knowing that they are always configured together in a Web application or ServletContext, only need to refer to each other by their relative URI /Login and /DisplayRooms, respectively. This allows their code to be written independent of where in the URL namespace the ServletContext actually is deployed. The ServletContext can be used to share information between all of the servlets within the Web application since they all share a common ServletContext.
24
www.hotel.ibm.com
/Rooms/HRApps/Personnel
/Hire /DisplayRooms/Login/Retire
ServletContext
/HRApps/Personnel
ServletContext/Rooms
Web container
servlet
Web containers and servlet context
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-47
Instructor Guide
Instructor notes:
Purpose —
Details — It is important that you tie the various Web applications to their corresponding ServetContexts. This is needed for the discussion of the request dispatcher.
Additional information —
Transition statement — Next: Servlet Objects (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-24. Servlet Objects (1 of 2) RD8107.5
Notes:
In this case the two clients are running the same servlet A.
Since both servlets are instances of Servlet A, they share the same ServletConfig. Also since they are in the same Web Application, they share the same ServletContext.
Each request (thread) has its own ServletRequest and ServletResponse object.
25
Client Sue
Client Bob
ServletRequestServletResponse
ServletConfig
ServletContext
ServletResponseServletRequest
Thread 1
Thread 2
Servlet A
Servlet objects (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-49
Instructor Guide
Instructor notes:
Purpose —
Details — The arrows represent references to the appropriate objects.
Additional information — The servlet API lets a servlet in one Web application access another Web application's ServletContext, but it cannot share the same ServletContext with another Web application.
Transition statement — Next: Servlet Objects (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-25. Servlet Objects (2 of 2) RD8107.5
Notes:
Assumptions:
• Servlet A and B are in the same ServletContext (Web application).
• Servlet A and B are running in the same JVM.
In this case the two clients are running different servlets in the same servlet context.
Since each request is for a different servlet, they each have their own ServletConfig. Since they are in the same Web Application they share the same ServletContext.
Each request (thread) has its own ServletRequest and ServletResponse object.
Note that the object diagram would look the same if both requests came from the same client.
26
Client Sue
Client Bob
ServletRequestServletResponse
ServletConfig
ServletContext
ServletResponseServletRequest
Servlet AThread 1
Servlet BThread 2
ServletConfig
Servlet objects (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-51
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Internationalization
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-26. Internationalization RD8107.5
Notes:
The client may optionally indicate to a Web server which language is preferred for a response. The getLocale() and getLocales() methods are provided in the ServletRequest interface to determine the preferred locale of the sender.
The setLocale() method of the HttpServletResponse class tells the Web browser what character set was used to build the output document. This sets the response object's charset value (part of the Content-Type response header).
27
Internationalization� Accepting Locale
�Communicated from the client using the Accept-Languageheader
�Use the getLocale() and getLocales() methods of the ServletRequest interface to get the locales client will accept content in
� Setting Locale�Use setLocale() method of the ServletResponse interface
to set the language attributes of a response�setLocale() method should be called before the
getWriter() method of the ServletResponse interface is called
�Default encoding of a response is ISO-8859-1 if none has been specified
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-53
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-27. Checkpoint RD8107.5
Notes:
Write down your answers here:
28
Checkpoint1. How do you forward a request to another servlet?2. How can you pass an object to a servlet to which you are
forwarding?3. How can you include dynamic content generated by
another servlet?4. What is the servlet context?5. What servlets share a servlet context?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-55
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
29
Checkpoint solutions1. Use the request dispatcher to invoke the target servlet:
getServletContext().getRequestDispatcher
(“/servlet/MyServlet”).forward(req, res);
2. Set the object as an attribute to the HttpServletRequest. The target servlet can then getAttribute() and cast it to the proper type. You call also use the session or the servlet context.
3. Use an include() to temporarily give control to another servlet.
4. The servlet context is an execution context of a group of related servlets. It allows for the servlets to use relative paths to refer to each other, and provides another way to share objects between servlets. Servlets within the same servlet context are defined in the same Web application.
5. Servlets defined within the same Web application share a servlet context.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-56 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 12-28. Unit summary RD8107.5
Notes:
30
Unit summary� Having completed this unit, you are able to:
�Discuss servlets as controllers (Model-View-Controller architecture)
�Look at the processing of request and response headers �Explain how servlets handle redirection�Discuss object sharing�Look at how servlets can forward to or include content from
other servlets �Explain the requirements for special characters in HTML
documents�Discuss multi-threading and thread safety issues�Describe some of the internationalization support for
servlets�Describe the use of and need for the servlet context
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 12. Servlet API (Part II) 12-57
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
12-58 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 13. Web Archive Deployment DescriptorEstimated time
00:25
What this unit is about
This unit describes the editor for the web.xml file provided in Rational Application Developer.
What you should be able to do
After completing this unit, you should be able to:
• Use the Application Developer web.xml editor to configure Web components within a Web module
• Define welcome and error pages for your Web module
• Have a better idea about the various elements of the web.xml deployment descriptor
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://publib.boulder.ibm.com/infocenter/radhelp/v7r5/index.jsp IBM Rational Application Developer V7.5.2 Help
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-1
Instructor Guide
Figure 13-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Use the Rational Application Developer Deployment Descriptor editor to configure Web components within a Web module
�Define Welcome and Error pages for your Web module�Understand the various elements of the Web Deployment
Descriptor (web.xml)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-3
Instructor Guide
Figure 13-2. WAR File RD8107.5
Notes:
The Sun Microsystems Java Servlet 2.2 specification introduced the Web application archive feature. A Web application is a group of HTML pages, JSP pages, servlets, and other resources, along with source files, optionally, that can be managed as a single unit. A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into an application server.
In addition to project resources, the WAR file includes a Web deployment descriptor file. The Web deployment descriptor is an XML file that contains deployment information, MIME types, session configuration details, and so forth, for a Web application. The Web deployment descriptor file (web.xml) provides information about the WAR file that must be shared with the developers, assemblers, and deployers in a Java EE environment.
3
WAR file� The Java Servlet 2.2 specification introduced the Web
application archive� A Web archive (WAR) file is a packaged Web application� A Web application is a group of HTML pages, JSP pages,
servlets, and other resources� WAR files also include a Web Deployment Descriptor file,
web.xml, which describes the Web module
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (General)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-5
Instructor Guide
Figure 13-3. Web Deployment Descriptor Editor (General) RD8107.5
Notes:
Display Name: A short name used to identify the Web application.
Description: Provides descriptive text about the Web application.
Session time out: Defines the default session time-out interval for all sessions created in this Web application, in minutes.
Distributable: When selected, it indicates that the Web application is programmed appropriately to be deployed into a distributed web container.
Note that sections represented by the GUI tabs (for example, Servlets, Filters, and Listeners) may also be directly accessed on the Overview page.
4
Web Deployment Descriptor editor (general)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (Pages)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-7
Instructor Guide
Figure 13-4. Web Deployment Descriptor Editor (Pages) RD8107.5
Notes:
Welcome pages: Add or delete Web application default welcome files, such as index.html.
Login: The Login values are used to configure the Web application authentication method, the realm name that should be used for this application, and the attributes that are needed by the Form login mechanism.
Realm name: specifies the realm name to use for HTTP Basic authorization.
Authentication method specifies the authentication mechanism for the Web application. As a prerequisite for gaining access to any Web resources that are protected by an authorization constraint, a user must be authenticated using the configured mechanism. Available authentication mechanisms include Basic, Digest, Form, and Client-Cert.
The Login page and Error page values are necessary for Form-based login. They are not activated for other login mechanisms.
Error pages: Specifies a mapping from an HTTP error code (which may be selected from a list) to the path of a resource in the Web application (which may be browsed).
5
Web Deployment Descriptor editor (pages)� Select Welcome File List to view the list of default files in the
details section.� Add or remove welcomes files from the details section.� To add items to the deployment descriptor, click Add and
select an item such as Error Page.� Specify Error Page details and save deployment descriptor.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Java Exception Types: Specifies a mapping from a Java exception type to the path of a resource in the Web application. The Exception value should be an the fully qualified class name of a Java exception type. Browsing is supported for both types and locations.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — HTTP Errors and Java Exception Types were handled in the same table in previous versions of Application Developer.
Transition statement — Next: Web Deployment Descriptor Editor (Servlets)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 13-5. Web Deployment Descriptor Editor (Servlets) RD8107.5
Notes:
Servlets: The Servlets page enables you to create a new servlet, add an existing servlet, or delete a servlet in the deployment descriptor. This page displays the declarative data of a servlet. The name listed in the Servlets table is the canonical name of the Servlet, and can be directly edited.
JSP files: JSP files compile into servlets, and they can be added to the list of Servlets. To do this, click Add. In the Create Servlet dialog, supply a name and, optionally, a description, initialization parameters, and URL mappings (a default mapping will be supplied for you based on the name). Check Use Existing Servlet Class, and click Browse. The New Servlet dialog will appear. At the very top, click the JSP radio button. A list of JSP files is displayed. Pick one, click OK, and you return to the Create Servlet dialog, where you can click Finish to finalize your selection.
JSP files may also be added through the Source tab as if they were Servlets, except that they require a <jsp-file> element instead of a <servlet-class> element.
6
Web Deployment Descriptor editor (servlets)� Add Item Servlet to specify a new
servlet� Provide Servlet details� To add additional configuration,
right click Servlet and select Add
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-11
Instructor Guide
If a JSP file is accessed only by its name (that is, no other URLs will map to it) and has no other special processing needs (such as initialization parameters or security roles), it does not need to be added to the Servlet list.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — Includes details about the selected servlet or JSP. Details listed include the servlet class or JSP file name, the display name (a short name for display purposes), and a description.
URL Mappings: Defines a mapping between a servlet or JSP file and a URL pattern. URL patterns must follow the rules specified in the Java Servlet API specification.
Initialization: Specifies the initialization parameters of the servlet or JSP file as a series of name-value pairs with optional descriptions.
Load on startup: Specifies that the servlet or JSP file should be loaded on the startup of the Web application. If a JSP file is specified with the Load on startup parameter, then the JSP file will be precompiled and loaded. The optional Load order value is a positive integer that indicates the order in which the servlet should be loaded. Lower-numbered servlets are loaded before higher-numbered servlets.
Security role references: Lists the security roles referenced in the Web application and lets you edit the security roles that are authorized to access the servlet. You can add or remove security roles. If you add a security role reference, you specify the role reference name, the role link, and a description.
Run as: Lists details of the selected servlet's run-as element.
Icons: Lets you view or change icons (small or large) used to represent the selected servlet or JSP file.
WebSphere Extensions: Lists and lets you change the details of the Servlet Extension for the selected servlet. You can add a new extension by clicking Add. The Add Markup Language entry wizard appears. Also, depending on the Servlet Version of the project you are working with, you can specify global and local transaction settings.
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (Security)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-13
Instructor Guide
Figure 13-6. Web Deployment Descriptor Editor (Security) RD8107.5
Notes:
The Security page enables you to identify and define constraints for the security roles that apply to Web resources.
Security Roles: Specifies a name and short description for each defined security role.
Security Constraints: Create or delete security constraints for specific security roles.
Web Resource Collection: Through the Web Resource Collection dialog, you can apply security constraints to Web resources and HTTP methods on those resources within a Web application. HTTP methods include GET, PUT, HEAD, TRACE, POST, DELETE, and OPTIONS. If no HTTP methods are specified, then the security constraint applies to all HTTP methods.
Authorized Roles: Indicates the user roles that should be permitted access to the specified resource collection.
User Data Constraint: Specifies that the communication between client and server should be None, Integral, or Confidential. None means that the application does not require any transport guarantees. A value of Integral means that the application requires that data sent
7
Web Deployment Descriptor editor (security)� Security Roles� Security Constraints
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
between the client and server is sent in such a way that it cannot be changed in transit. Confidential means that the application requires that the data be transmitted in a manner that prevents other entities from observing the contents of the transmission. In most cases, the presence of the Integral or Confidential flag indicates that the use of SSL is required.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (Filters)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 13-7. Web Deployment Descriptor Editor (Filters) RD8107.5
Notes:
Filters provide preprocessing of requests before they reach servlets, and postprocessing of servlets responses. They are described in detail in Unit 23.
Filter class: the name of the filter's implementing class.
Name: the filter's name.
URL mappings: URL patterns of resources to which this filter is mapped.
Servlet Mappings: names of servlets to which the filter is mapped.
Initialization: names and values of initialization parameters used by the servlet.
Icons: small and large images used to represent the filter in a GUI tool.
8
Web Deployment Descriptor editor (filters)� Details� Mappings
�URL�Servlet
� Initialization� Icons
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Note there is currently an issue in Rational Application Developer. If you create a filter, and then open the Deployment Descriptor Editor, it will indicate that the file needs to be saved. You need to save the file to save the filter.
Transition statement — Next: Web Deployment Descriptor (References)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 13-8. Web Deployment Descriptor (References) RD8107.5
Notes:
The References page specifies a Web application's references to enterprise beans, web services, and other resources. The data collected varies by reference type.
9
Web Deployment Descriptor (resource references)� Define references to:
�EJB components and Web services�External resources�Message destinations�Administered objects
� DistributedMap� Queue� Topic� DataSource
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (Extensions)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 13-9. Web Deployment Descriptor Editor (Extensions) RD8107.5
Notes:
In the Extensions page of the Web deployment descriptor editor, you can:
• Modify various general settings. For example, you can specify whether
- Reloading is enabled
- File serving is enabled
- Directory browsing is enabled
- To serve servlets by classname
- Precompile JSPs
- Automatic request coding is enabled
- Automatic response coding is enabled
- Automatic filter loading is enabled
• Add or remove MIME filters
• Add or remove JSP attributes
10
WebSphere Extensions editor� WebSphere only extensions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-21
Instructor Guide
• Add or remove file serving attributes
• Add or remove invoker attributes
• Add, remove or edit servlet caching configurations
Here are some more details:
Mime Filters: Filters transform either the content of an HTTP request or response and can also modify header information. MIME filters forward HTTP responses with a specified MIME type to one or more designated servlets for further processing. To create a new MIME filter, click Add, and supply a target filter and MIME type. To edit an existing filter, selected it and overtype the values in the Target and Type fields.
JSP Attributes: These specify options for the JSP precompiler. To create a new attribute, click Add and specify the name and value of the attribute. To change an attribute, select it and overtype the values in the Name and Value fields.
WebSphere Application Server and Rational Application Developer currently support the following options for the JSP compiler:
keepgenerated: Specifies whether the source code of the servlet created by compilation of the JSP page is kept on the file system. If this value is True, the source code is kept. Otherwise, it is deleted as soon as the servlet code has been compiled. If the source code is deleted, only the .class file is available.
scratchdir: Specifies the directory in which the servlet code is generated. If no string is specified, code is generated in <profile_home>\temp\<hostname>\ <application_server_name>\<application_name>\<webmodule_name>.
jdkSourceLevel: Specifies the JDK level to use during page compilation. Valid values are: 13, 14 and 15.
File Serving Attributes: Specifies properties for servlets that use file serving extension.
Invoker Attributes: Specifies properties for servlets that implement the invoker behavior.
Servlet Caching Configurations: Dynamic caching can be used to improve the performance of servlet and JavaServer Pages (JSP) files by serving requests from an in-memory cache. Cache entries contain the servlet's output, results of the servlet's execution, and metadata. To open the Add Servlet Caching wizard, click Add. To edit a configuration, select it from the list box and click Edit to open the Edit Servlet Caching wizard.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Web Deployment Descriptor Editor (Source)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-23
Instructor Guide
Figure 13-10. Web Deployment Descriptor Editor (Source) RD8107.5
Notes:
The Source page permits direct editing of the web.xml source file. This may be required to:
Fix errors,
Make global changes, or
Use features not currently supported by Deployment Descriptor editor.
Content-assist is available via CTRL-space, even for features not supported by the Deployment Descriptor editor.
11
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"…>
<display-name>CS01 Web Module</display-name>
<servlet>
<display-name>Command Servlet</display-name>
<servlet-name>CommandServlet</servlet-name>
<servlet-class>
com.ibm.servlet.CommandProcessingServlet
</servlet-class>
<init-param>
<param-name>controller</param-name>
<param-value>
com.ibm.exam.controller.ExamHttpController
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CommandServlet</servlet-name>
<url-pattern>ExamCommand</url-pattern>
</servlet-mapping>
…
</web-app>
Web Deployment Descriptor editor (source)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Other Web Deployment Descriptor Editor Pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-25
Instructor Guide
Figure 13-11. Other Web Deployment Descriptor Editor Pages RD8107.5
Notes:
JSP property groups allow you to set properties for a group of JSPs that match a URL pattern.
- Ignore EL
- Allow scripting
- pageEncoding
- Is XML
- Automatic header and footer includes
12
Web Bindings Editor� Web Bindings Editor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Note that the Variablesin this version of Application Developer subsumes the purposes of the Environment, Listeners, Parameters andMIMEtabs of previous versions.
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-27
Instructor Guide
Figure 13-12. Checkpoint RD8107.5
Notes:
Write down your answers here:
13
Checkpoint1. How do you register a servlet in a Java EE Web
application?2. What does load on startup mean?3. What triggers can you configure to invoke an error page?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
14
Checkpoint solutions1. Servlets are declared as Web components in the web.xml
Deployment Descriptor. 2. To load a servlet at start-up accomplishes two things. First,
servlets that have an involved initialization can be ready to go when the first request for them is made. Second, by permitting the specification of load order, it is possible to configure a servlet whose principal task is to initialize the JVM( for example, by loading JDBC drivers).
3. Error pages can be triggered on a particular status code or Exception.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-29
Instructor Guide
Figure 13-13. Unit summary RD8107.5
Notes:
15
Unit summary� Having completed this unit, you are able to:
�Use the Rational Application Developer Deployment Descriptor editor to configure Web components within a Web module
�Define Welcome and Error pages for your Web module�Understand the various elements of the Web Deployment
Descriptor (web.xml)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 13. Web Archive Deployment Descriptor 13-31
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
13-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 14. Session State Storage IssuesEstimated time
00:30
What this unit is about
Since servlets and JSP pages are stateless, any application state specific to a user must be stored outside them. This information is called session state.
Determining what to do with this session state is one of the most challenging problems in servlet programming.
In this unit you discuss the issues involved in managing session state.
What you should be able to do
After completing this unit, you should be able to:
• Identify issues related to sessions
• Examine options for session management
• Examine special concerns with cluster configurations
How you will check your progress
Accountability:
• Checkpoint • Discussion
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-1
Instructor Guide
Figure 14-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Identify issues related to sessions�Examine options for session management�Identify the advantages and disadvantages of each option�Examine special concerns with cluster configurations
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — In this topic you discuss several approaches to session data management.
Details — When you talk about session data management, you are not just talking about using the HttpSessionobject. The use of HttpSessionis just ONE way available to developers when trying to manage session data. Make sure your students understand you are talking about more than just HttpSessionin this topic.
Additional information —
Transition statement — Look again at why you need to worry about session data when designing and implementing our servlets and JSP pages.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-3
Instructor Guide
Figure 14-2. The Session Problem RD8107.5
Notes:
HTTP is a stateless protocol. It does not have the notion of a connection as other protocols (such as with TCP/IP sockets, LU6.2, and so forth) have. Each HTTP request-response pair is a unique entity unto itself and does not have a relation (within the protocol) to other request-response pairs. But a Web site needs to have certain client information shared among all of the servlets or CGI programs that provide its dynamic content. For instance, the servlet that displays the contents of a shopping cart must know what has been previously placed in the shopping cart. This transient shared information is often called session data because it represents the connection (a user session) between the various programs or servlets that a user will touch during a visit. This should not be confused with transaction data that is permanently stored (usually in a database).
Don't think of this as just HttpSession data; the use of the HttpSession support is just one way of managing the session state and session data.
3
The session problem� Servlets and JSP pages should be stateless
�They should not have instance variables�They support multiple concurrent threads
� Application state information specific to a user must be stored outside of the servlet�This is called Session State�Determining what to do with it is one of the most
challenging problems in servlet programming�Session state is session data, and is only used for a set of
linked Web pages (your Web application)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — You cannot manage the client's data from within the servlet and JSP page.
Details — Since client data must be stored outside of the servlet or JSP page, you are forced to have the client involved in the saving of the client related data. There are several approaches to this:
• Hidden fields
• Cookies
• URL Rewriting
Additional information —
Transition statement — To make your lives even more interesting, you have to worry about how your Web-based application scales to large traffic volumes. This could entail multiple systems processing servlets. Another twist to the session sharing problem is how to share data when different parts of the Web application may run on different systems during its life.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-5
Instructor Guide
Figure 14-3. The Load Balancing Complication RD8107.5
Notes:
For instance, a common strategy is to pin requests from a client (by IP address) to a particular server. When the first request from a client comes in, the router adds a table entry that maps that client to a particular server. From then on, all subsequent requests from the client are routed to that same server.
However, many ISPs (like AOL) use a reverse-proxy strategy that makes it appear as though ALL of their clients were coming from a very small number of IP addresses. This defeats the purpose of what you were trying to accomplish.
4
Load Balancing Router
Browser
WebSphere Application Server 1
WebSphere Application Server 2
The load balancing complication� In high-traffic sites, HTTP requests are spread across multiple
servers�Any application strategy that restricts even distribution of
requests is unacceptable�Your application should be server-independent
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — As you manage session state, you need to keep load balancing in mind.
Details — As sites grow larger, you may need multiple servers to service customer requests. If your data sharing strategy ties a client to a specific server, this can impact your ability to fully utilize your Web systems. You want to maintain server independence. You don't want to pick a session state design that doesn't scale as you add new servers to your system.
Additional information —
Transition statement — Take a look at some of the things you can do to keep your Web applications server-independent.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-7
Instructor Guide
Figure 14-4. The Load Balancing Solution RD8107.5
Notes:
In Web sites that must demonstrate server independence it becomes necessary to determine how to share session data between different machines running the same servlet-based applications.
WebSphere Application Server V6.1 provides server-side techniques in its support of HttpSession through features such as distributed sessions (database persistence or memory-to-memory to replication) and session affinity. Distributed sessions allow data to be shared between machines in a cluster. Session affinity ensures that client requests continue to be serviced by the same server in order to improve the likelihood of using cached session data with the attendant performance improvement.
5
The load balancing solution� Avoid tying a user to a particular machine:
�Store session data on the client rather than the server�Store session data on a shared third-tier machine�Store session data between the servers with a peer-to-peer
protocol� WebSphere Application Server features
�Store HttpSession data in a shared database (distributed session database persistence)
�Store HttpSession data between servers (memory-to-memory replication)
�Session affinity
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — This foil looks at things you can do to keep your Web applications server-independent.
Details — The first item here is client centric. The session (client) data is stored on the client's system and is NOT kept in the server. Since all of the data needed for that client's session is kept on the client, your Web application is not tied to a specific server. If the session data you are storing is just the session ID, then you have to be concerned with whether the session ID and its related session object can be shared across multiple servers.
The next two items are storing and managing the data between the server systems. Putting the session (client) data on a shared database allows all of the server systems to access the data. Of course there are a lot of database sharing issues that have to be addressed by your Database Administrators. The last option lets the server systems communicate with each other via some (unspecified) peer protocol. They can use this peer-to-peer protocol to share the session data.
WebSphere Application server provides support of sharing data between server systems with support for distributed sessions and session affinity when using HttpSessions.
Additional information — Don't spend too much time here; you will talk about each of these in detail in later foils.
Transition statement — It is time to review what you've done so far and look at where you are headed.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-9
Instructor Guide
Figure 14-5. Session Strategies - Review RD8107.5
Notes:
You continue looking at these strategies after you have covered the topics of Cookies, URL Rewriting, and HttpSession in more detail.
6
�Cookies�Hidden Fields�URL Rewriting
�Content Based Routing�Store state in a database�WebSphere Application Server Distributed Sessions�WebSphere Application Server Session Affinity
Client Side
Server Side
Session strategies: review� Session state can be stored on either the client or the server� Examine several session management strategies and figure
out where each applies
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Bridge between the overview and the detailed discussion.
Details — We've talked about storing session data in the client and saving it in the server. In the next few units you cover these approaches in detail and summarize the pros and cons of each approach after the detail units.
Additional information —
Transition statement — The next units will look at Cookies, HTTP Sessions, and URL Rewriting. The unit following those summarizes the pros and cons of each approach.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-11
Instructor Guide
Figure 14-6. Checkpoint RD8107.5
Notes:
Write down your answers here:
7
Checkpoint1. What is the session problem?2. How does a clustered configuration pose special session
management issues?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
8
Checkpoint solutions1. HTTP protocol is stateless, so servlets and JSP pages
should be stateless, yet you may want to maintain state with a particular client across multiple interactions.
2. In a typical situation, you are maintaining a session on a single server or JVM. When you move to a clustered configuration, you want to maintain flexibility to service a request on any server, not just on the server that handled the initial request.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-13
Instructor Guide
Figure 14-7. Unit summary RD8107.5
Notes:
9
Unit summary� Having completed this unit, you are able to:
�Describe the need to manage session data �Identify the two major approaches to session management:
� Server-side� Client-side
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 14. Session State Storage Issues 14-15
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
14-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 15. Cookie APIEstimated time
00:20
What this unit is about
Even though cookies are not part of the HTTP flow, they are commonly used in building Web applications, and are an IETF standard (RFC 2109). This topic discusses the methods available within the Servlet API to create and manipulate cookies.
What you should be able to do
After completing this unit, you should be able to:
• Describe what a cookie is
• Describe the use of cookies for session management
• Describe how cookies are implemented in the architecture
• Examine the cookie API
• Explain how long cookies last
How you will check your progress
Accountability:
• Checkpoint
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-1
Instructor Guide
Figure 15-1. Unit objectives RD8107.5
Notes:
The purpose of this topic is to become familiar with HTTP cookies and how to work with them within the Servlet API.
2
Unit objectives� After completing this unit, you will be able to:
� Describe what a cookie is� Describe the use of cookies for client (or session)
management� Explain how cookies are implemented in the architecture� Examine the cookie API� Explain how long cookies last
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — General discussion of cookies.
Details — Client-session management deals with keeping track of client data. This could be as simple as keeping some personalized data about the client in the cookie (such as the login ID), or it could be data that needs to be maintained about this client for this session (a set of related requests, such as a shopping cart). Note that you are not yet discussing HttpSessionmanagement here, although cookies can be used by the application server for session tracking in support of the HttpSessionAPI. You talk about HttpSessionlater.
Additional information —
Transition statement — Next: Cookies
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-3
Instructor Guide
Figure 15-2. Cookies RD8107.5
Notes:
A cookie is a piece of data passed between a Web server and a Web browser. The Web server sends a cookie that contains data it requires the next time the browser accesses the server. The client returns the cookie on each subsequent request. This is one way to maintain the state between a browser and a server.
Cookies come in two flavors: persistent and non-persistent. They have a number of properties, including a name and a value. Cookies are frequently used to save user preferences and identification information.
Note that most browsers allow cookies to be disabled at the user's option. Don't write all of your application code with the assumption that they are available (more on how WebSphere handles that later).
3
Cookies� Cookies are a way to place persistent information on the client
machine (accessible from the browser)�A good way to handle preferences or shortcuts
� Cookies have a name and a value
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Cookies are a way to deal with the stateless nature of the HTTP protocol.
Transition statement — Next: Cookie API
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-5
Instructor Guide
Figure 15-3. Cookie API RD8107.5
Notes:
You can create a Cookie through the two-argument constructor.
Cookies are returned to the browser by adding them to the HTTP response stream. This is done by the addCookie() method on the HttpServletResponse object. To retrieve incoming cookies from the browser, use the getCookies() method on the HttpServletRequest object. Be aware that you cannot ask for the cookie with a specific key. You must ask for all cookies and find the specific one that you are interested in.
All cookie properties are exposed via getter and setter methods.
4
Cookie API� Creating cookies
�Cookie(String name, String value)� Sending a cookie back to the browser
�HttpServletResponse.addCookie(Cookie aCookie)� Retrieving cookies
�HttpServletRequest.getCookies()� Retrieving a cookie’s name
�aCookie.getName()� Retrieving a cookie’s value
�aCookie.getValue()� Changing a cookie's value
�aCookie.setValue(String)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Remind them that the browser (client) ultimately controls whether cookies are accepted. The servlet doesn't know whether the cookies were accepted until the next request is received and no cookies are returned. This topic is covered later in the unit, including some sample code that detects if the browser is accepting cookies.
Although the request returns all cookies, it really only returns all cookies that originated from the same domain.
Transition statement — Next: Cookie Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-7
Instructor Guide
Figure 15-4. Cookie Usage Example RD8107.5
Notes:
This simple example shows getting a cookie to determine which choice of two types of output to use. User preferences are good candidates for storage in cookies.
doGet() throws exceptions that were not included in the code above.
5
Cookie usage examplepublic void doGet(HttpServletRequest req,
HttpServletResponse res) {
String userType = "novice";
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i=0; i<cookies.length; i++) {
if(cookies[i].getName().equals("userType"))
userType = cookies[i].getValue();
}
}
if (userType.equals("expert"))
// do expert HTML
else // do novice HTML
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Proper Cookie Usage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-9
Instructor Guide
Figure 15-5. Proper Cookie Usage RD8107.5
Notes:
Cookies can be disabled on the client browser. A client may do that if concerned about privacy issues with the use of cookies. Thus, you should use cookies with the respect of the client in mind.
On the client, cookies which are persisted (that is, which have maxAge > 0) can be viewed and altered by the client.
6
Proper cookie usage� Because cookies are stored as plain text on the client
machine, cookies can be viewed and altered by the client� Cookies should not be used for information such as:
�Validation information�Secure information (credit card numbers and the like)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — Note that HttpSessionsupport has not been discussed yet. If this is a normal class, you cover that in a later lecture topic. If this is a custom offering and the HttpSessionsupport is NOT going to be covered, you should about it here to give this slide some context.
Additional information —
Transition statement — Next: Cookie Applicability
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-11
Instructor Guide
Figure 15-6. Cookie Applicability RD8107.5
Notes:
A MaxAge of 0 is a request for the browser to delete the cookie.
Two other properties control which URLs a cookie is to be delivered to. Domain specifies which hosts the cookie can be delivered to (the default is the host name of the server that created the cookie). If there is a tail match, the cookie will go through path matching to see if the cookie should be sent to the Web server. For example: A domain attribute of .ibm.com will match host names www.ibm.com, www.ilscs01.ibm.com, and so forth. Only hosts within the specified domain are allowed to set a cookie for that domain. The domain name must have two or three periods to prevent domain names of the form .com or .org. Domain names that don't fall within the special top-level domains (COM, EDU, NET, ORG, GOV, MIL, and INT) must have three periods.
Path specifies which subset of URLs in a domain are valid for a cookie. Once the cookie has passed domain matching, the path name of the URL is compared with the path value specified in the cookie. If there is a match, the cookie is valid and is sent to the Web server for that request. The path /acc would match /accounting, /acc/index.html, and so forth. If
7
Cookie applicability� Cookies have an expiration date
�setMaxAge(int expiryInSeconds)
� Default expiration date is -1�This means that the cookie is not stored persistently�It lasts only as long as the browser is open
� Can restrict the applicable URLs to which a cookie will be sent�setDomain(String)
�setPath(String)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
the path is not specified, it is assumed to be the same path as the document that contains the cookie.You cannot detect if the client's browser is accepting cookies in one HTTP request. Your application has to set the cookie on one response and then try to read it back in another request. If the cookie is on the second request, you know the browser accepted the cookie.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-13
Instructor Guide
Instructor notes:
Purpose —
Details — Transient and expired cookies will be deleted by the browser according to its own approach. When a cookie is returned, only the key-value is retrieved; all other settings (maxAge, domain, and so forth) are not available.
Additional information — More information on testing browsers for cookies enablement is present in later slides in this unit.
Transition statement — Next: Client Data and Session Management by Cookies
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 15-7. Client Data and Session Tracking with Cookies RD8107.5
Notes:
Cookies can be used to manage client data, such as maintaining client-side session state data.
When using the HttpSession support in the Servlet API, the application server's Session Manager can use cookies to store a session ID on the browser. This cookie is not stored persistently. On WebSphere Application Server, the default name of this cookie is JSESSIONID, as mandated by the Servlet specification.
8
Client data and session tracking with cookies� Cookies can be made to persist within or across browser
interactions� Cookies are passed to the Web server in the header of the
request� Any updates are passed back in the header of the response� Session data tracking via HTTP cookies is the most commonly
used session tracking mechanism�Required to be supported by all Web containers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Checking If Cookies Are Accepted on Browser
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 15-8. Checking if Cookies Are Accepted on Browser RD8107.5
Notes:
Most browsers allow the users to configure whether cookies are accepted or declined. There is no single method that can be used to check the user's browser configuration, but a program can send a test cookie and the attempt to read that test cookie to determine if cookies are being accepted or declined.
9
Checking if cookies are accepted on browser� Most browsers can be configured to accept or decline cookies� There is no single method to directly check the browser’s
cookie configuration� To check the browser’s cookie configuration:
�Use the addCookie() method to send a test cookie to the browser
�Use getCookies() method to read the test cookie�Execute appropriate code based on the result of
getCookies()
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Checking Cookie Configuration: Sample Code
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 15-9. Checking Cookie Configuration: Sample Code RD8107.5
Notes:
This slide illustrates one way to check if a user's browser is configured to accept cookies. This code would typically be in a servlet's doPost() or doGet() method.
When the servlet initially handles the request, the URL does not contain a parameter of name cookietest, so the outer if clause is executed to add a new test cookie and instruct the browser to redirect to the current URL, but with a cookietest parameter added to the URL. Note that this URL has the session information encoded (if necessary) with the response.encodeRedirectURL() method.
After the browser performs the redirect, this code is executed once again; the cookietest parameter now exists, so the outer else clause is executed. Within the else clause the code attempts to get cookies from the browser. If the return from the getCookies() method is not null, then cookies are being accepted by the browser. The code can then take the appropriate action based on the setting; the sample code forwards control to different servlets that are coded to continue processing with or without cookies enabled.
10
Checking cookie configuration: sample code// Check to see if cookietest parameter is set
if (req.getParameter("cookietest") == null) {
resp.addCookie(new Cookie("CookieTest", "ok"));
String url = req.getRequestURI() + "?cookietest=ok";
resp.sendRedirect(url);
return;
}
// Callback from sendRedirect() above - check for cookie
ServletContext ctx = getServletContext();
if (req.getCookies() != null) {
// Cookies were accepted, so handle appropriately
ctx.getRequestDispatcher("/HandleCookie").
forward(req, resp);
} else {
// Cookies were declined, so handle appropriately
ctx.getRequestDispatcher("/HandleNoCookie").
forward(req, resp);
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 15-10. Checkpoint RD8107.5
Notes:
Write down your answers here:
11
Checkpoint1. What types of data are best not kept in a cookie?2. Why use cookies?3. How do you send a cookie to a browser?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-21
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
12
Checkpoint solutions1. Any sensitive or confidential data should not be kept in
cookies, because they are transmitted as part of the header (and not encrypted), and are stored unencrypted on the browser’s file system.
2. Cookies are used to keep persistent information about a session between a Web browser and a Web server. You can use a cookie to tie several HTTP request-response interactions together to build a Web application. There is more information about this when you talk about session management.
3. Your servlet creates a Cookie and adds it to the HttpServletResponse. The cookie is then returned to the Web browser. The Web browser, however, can throw it away if the user has turned off cookie support.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 15-11. Unit summary RD8107.5
Notes:
13
Unit summaryHaving completed this unit, you are able to:� Describe what a cookie is� Describe the use of cookies for client (or session)
management� Create a cookie and add it to a response� Find a cookie in a request� Set cookie properties such as:
�Name
�Value
�Age
�Domain
�Path
� Test for cookie support in a browser
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 15. Cookie API 15-23
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
15-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 16. HttpSession: Management of Application DataEstimated time
00:30
What this unit is about
In this topic you learn how the servlet API supports session data. The primary class, HttpSession, can be used to help your servlet manage any session data that needs to be tied to the current client your servlet is interacting with. This would include keeping track of the client’s logged in state or could be used in an online store to keep track of the customer’s shopping cart.
What you should be able to do
After completing this unit, you should be able to:
• Consider the task of managing per client application data (Session Management)
• Describe the use of HttpSession to maintain a user session
• Describe how object sharing is implemented in the servlet environment
• Describe the various ways to manage application state
How you will check your progress
Accountability:
• Checkpoint • Lab exercise
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-1
Instructor Guide
Figure 16-1. Unit objectives RD8107.5
Notes:
The purpose of this topic is to look at application state management, known as session data, and the API provided as part of the Java Servlet API to support it.
2
Unit objectives� After completing this unit, you will be able to:
� Discuss the task of managing client application data � Session management with the WebSphere Application Server
Session Manager tool� Describe the use of HttpSession to maintain a user
session� Explain how object sharing is implemented in the servlet
environment� Describe the various ways to manage application state
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Look at how the HttpSessionobject is used to provide session management support for your servlets, and also look at sharing objects between servlets.
Details — The HttpSessionclass is used by your servlets to keep track of session data (session information about the specific client you are connected to). Closely related to this is the need to share data between multiple servlets. There are several scopes for this sharing, the session level being one of them.
Additional information —
Transition statement — This starts the discussion of session management.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-3
Instructor Guide
Figure 16-2. Session Management (1 of 2) RD8107.5
Notes:
As you have seen, Servlets should be stateless to remain thread-safe. This means that they can have no instance variables.
However, per-client application state needs to be managed somewhere outside of the servlet. An example of such data includes a customer shopping cart.
A client session is the scope over which data needs to be maintained.
3
Session management (1 of 2)� Sessions provide a way to identify a user across more than
one page request or visit to a Web site, and to store information about that user
� Web applications must manage state information:�Current customer, shopping cart, and so forth�Application involves several servlets�Servlets need to be stateless
� Multiple implementation technologies including:�HttpSession �HTTP Cookies�HTML Hidden Field�URL Rewriting
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Cookies, hidden fields, URL rewriting, and the HttpSession support are all different ways to support session management. In the discussion of cookies and hidden fields you are talking about writing your own session support using these technologies (and NOT using the HttpSessionsupport).
If you use the HttpSession class, this support is provided for you. HttpSession will use either cookies or URL rewriting under the covers to implement the session management.
Transition statement — Next: Session Management (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-5
Instructor Guide
Figure 16-3. Session Management (2 of 2) RD8107.5
Notes:
An HTTP session is a short-term (transient) relationship established between a client browser and a Web application server through which data can be maintained. It lives as long as both the client and the server maintain the reference to the relationship.
Session information is scoped only to the current Web application (ServletContext), so information stored in one context is not directly visible in another.
The Servlet API provides the state management interface in javax.servlet.http.HttpSession. This interface allows servlets to:
View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
Bind objects to sessions, allowing user information to persist across multiple user connections
An instance (a particular client's data) is assigned a unique ID. This session ID then is all that needs to be exchanged between the browser and Web server.
4
Session management (2 of 2)� The HttpSession interface, part of the Servlet API, provides
an interface for managing application state on the server� In applications that are marked as distributable, the session
data objects placed into the HttpSession object must be serializable (they must implement the Serializableinterface)�WebSphere's HttpSession implementation allows
session data to be placed in a shared database (or replicated between servers), and makes clustering of servers simpler and more robust
� A session:�Represents a client-server HTTP connection�Lifetime spans multiple servlets and page requests�Is identified within requests via a Session identifier
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
WebSphere Application Server's implementation allows session data to be shared across different Web containers. This is allowed by the servlet specification from Sun, but is not required.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — If an application is marked as distributable, it means the servlets involved may run on different servers or JVMs. The J2EE specification is vague as to how a given implementation allows you to mark the application as distributable. This differs from implementation to implementation. In WebSphere Application Server, this is an option when you define the application to WebSphere Application Server.
Transition statement — Next: Session Usage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-4. Session Usage RD8107.5
Notes:
Access to the session object is via the HttpServletRequest object. A request is on behalf of a specific client. Code can ask the request object for the session object associated with the current client via the getSession method. If a session object exists for the current client, it is returned by this method. The parameter (if specified) determines the behavior of the method, if no current session exists for the client. If the parameter is true, a new session object is created on behalf of the client. If false, a null object is returned. There is a no-parameter version of this method which is equivalent to getSesstion(true).
By default, WebSphere Application Server uses a cookie as the mechanism to track the session id. A servlet should be able to handle cases in which the client chooses not to join a session, such as when cookies are intentionally turned off. Until the client joins the session, isNew returns true. If the client chooses not to join the session, getSession will return a different session on each request, and isNew always returns true.
Sessions can also be managed by using URL rewriting, but additional programming is needed by the servlets to ensure that all links are properly encoded to support the URL rewriting.
5
Session usage� Servlet asks to bind to the Session object representing the
current session:�A session is requested –request.getSession(boolean create)
�The method returns the current HttpSession, if it exists�If create is true (or no parameter is specified) AND no
current Session exists, a newly created session is returned� The session is unavailable when:
�The client browser is closed�The session is explicitly invalidated�The session times out
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: HttpSession Data Store
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-5. HttpSession Data Store RD8107.5
Notes:
The purpose of the HttpSession object is to act as a place to store arbitrary application data. This data is stored as <name, value> pairs. The methods to access the data are getAttribute() and setAttribute().
Standard session properties include information about the session, such as the session ID, creation time, and last date accessed.
The Application layer data can make the session object large. Be careful not to store large objects, such as graphs, as this can degrade performance. Instead, minimize the size by storing keys to data stored in other sources.
6
HttpSession data store� HttpSessions store application-specific information
�Stored as <"key", object> pairs� void setAttribute(String, Object)
� Object getAttribute(String)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Sessions at Run Time - Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-6. Sessions at Run Time - Server RD8107.5
Notes:
In WebSphere Application Server there is a Session Manager associated with each web container (application server process which can service Servlets, JSP pages, and so forth).
This Session Manager is responsible for keeping track of all of the currently active sessions by session ID. Thus the session manager logically maintains a large table of session IDs that reference the session objects which in turn hold references to application data.
7
ID valueMKA42O... SessionR1
...
...YM4YLEI... SessionA3
SessionA3key value"customer" aCustomer"name" "Bob"
Application ServerSession Table
Sessions at run time - server� HttpSession objects are
managed by the Web container� They are registered by ID� The ID must be delivered to the
client initially, and presented back to the server on subsequent requests
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Sessions at Run Time - Client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-7. Sessions at Run Time - Client RD8107.5
Notes:
The assumption here is that sessions are represented by cookies on the client, which is the best solution.
You can also use URL rewriting-- this is supported via the encodeURL() method on the HttpServletResponse Interface.
URL rewriting is where the session ID is appended to the request URL.
Note that JSP pages do not automatically use URL rewriting. Also, DHTML-generated URLs are difficult to configure to participate in a non-cookie-based session.
WebSphere Application Server may also be configured to provide session tracking with SSL information. This technique, however, is only supported for the application server's internal HTTP server, IBM HTTP Server, and the iPlanet Web server.
8
Cookie List
Browser
cookie name value domain
"JSESSIONID" YM4YLEI... .ibm.com
Sessions at run time: client� The preferred (default) delivery
vehicle for session ID is a transient cookie
� Alternative URL rewriting is supported by HttpServletResponse
�No automatic support in JSP pages
�Requires ad hoc support for client-side script generated URLs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-15
Instructor Guide
Instructor notes:
Purpose —
Details — One of the problems with choosing URL rewriting as the method for session tracking is that all your hrefs and links need to have this session ID appended. If the ID is not appended on a subsequent request, the session is invalidated or lost.
Additional information —
Transition statement — Next: Sessions at Run Time
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-8. Sessions at Run Time RD8107.5
Notes:
The end-to-end picture has a session ID stored in a Cookie on the browser and the session object stored on the server, managed by the Session Manager, and associated with the session ID.
9
ID valueMKA42O... SessionR1
...
...YM4YLEI... SessionA3
SessionA3key value"customer" aCustomer"name" "Bob"
Application ServerSession Table
cookie name value domain
"JSESSIONID" YM4YLEI... .ibm.com
Cookie List
Browser
Sessions at run time
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Session Invalidation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 16-9. Session Invalidation RD8107.5
Notes:
One problem with session management is the conceivably large number of sessions created with little ownership for the responsibility of cleaning up abandoned sessions. A client can choose to go to another site or just close its browser - orphaning the corresponding session data.
Sessions are also assigned a maxInactiveInterval (or time to live). The session manager keeps track of inactivity on sessions. When a session has been inactive for longer than its maxInactiveInterval, the manager will invalidate the corresponding session.
Within WebSphere Application Server you can set a maximum number of sessions. The base in-memory session pool size number has different meanings, depending on session support configuration:
When sessions are being stored in memory, session access is optimized for up to this number of sessions. When sessions are being stored in a database, it also specifies the cache size and the number of last access time updates that are saved in manual update mode.
10
Session invalidation� Release HttpSession objects when finished
�An Application Server can only maintain a certain number of HttpSession objects in memory
� Sessions can be invalidated either programmatically or through a timeout�session.invalidate
�Removes all values from the session� The session timeout (inactive interval) can be set for the
application server as a whole�The default timeout is 30 minutes
� Also session.setMaxInactiveInterval(int) can provide session-specific timeout value
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-19
Instructor Guide
After the base in-memory session pool size is surpassed, sessions are simply not cached, and session updates are automatically sent back to the database, without checking for their presence in the cache.
Note that increasing the base in-memory session pool size can necessitate increasing the stack sizes of the Java processes for the corresponding WebSphere application servers. By default, the number of sessions maintained in memory is specified by base in-memory session pool size. If you do not wish to place a limit on the number of sessions maintained in memory and allow overflow, set this value to true.
Allowing an unlimited amount of sessions can potentially exhaust system memory and even allow for system sabotage. Someone could write a malicious program that continually hits your site and creates sessions, but ignores any cookies or encoded URLs and never utilizes the same session from one HTTP request to the next.
When overflow is disallowed, the Session Manager still returns a session with the HttpServletRequest's getSession(true) method if the memory limit has currently been reached, but it will be an invalid session that is not saved in any fashion.
With the WebSphere Application Server extension to HttpSession, com.ibm.Websphere.servlet.session.IBMSession, there is an isOverflow() method which returns true if the session is such an invalid session. An application could check this and react accordingly.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Session Invalidation Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-21
Instructor Guide
Figure 16-10. Session Invalidation Example RD8107.5
Notes:
When a session is invalidated, it causes all of the values to be removed.
When the limiting number of HttpSessions in memory is reached, they are serialized and swapped to disk. In a high-volume system, the cost of serializing many abandoned HttpSessions can be quite high.
11
Session invalidation exampleimport java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ApplicationLogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession mySession = req.getSession(false);
// Invalidate session
if (mySession != null) {
mySession.invalidate();
}
// Perform additional application logoff processing
// and send output response to browser here
}
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Session Examples
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-23
Instructor Guide
Figure 16-11. Session Examples RD8107.5
Notes:
To see the ease of use of sessions, you look at a simple business-to-consumer (B2C) application, in this case, an online book sales site. The service of selling today's specials is implemented using two servlets. A Web page offers the selections; the user selects one or more books to purchase and submits that request. Our BookChoiceServlet handles this request. The customer is then prompted for name, ship to address, and credit card information to process the order. Our CreditInformationServlet controls this order processing.
Remember the design rule -- each servlet should do ONE thing and do it well. That design is shown in the two servlets.
12
Session examples� You follow a simple e-commerce example using the Session
API to run an online bookstore� There are two Servlets:
�BookChoiceServlet� Allows the user to select choices� Can browse without purchasing
�CreditInformationServlet� Takes credit card information� Confirms and processes the order
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Bookstore Domain Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-25
Instructor Guide
Figure 16-12. Bookstore Domain Classes RD8107.5
Notes:
These are very simple, standard domain objects. They could all be JavaBeans, but that's not a requirement.
13
Address
zip : Stringcity : Stringstate : StringstreetAddress : String
SaleLineItem
price : doubleitemName : String
customer
Customer
name : StringcreditCardNumber : StringcreditCardExpiration : String
Order
lineItems
1
1
1 0..*
0..*
1
Bookstore domain classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Book Choice Servlet (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-27
Instructor Guide
Figure 16-13. Book Choice Servlet (1 of 2) RD8107.5
Notes:
The key here is the order: (1) Get the session (2) Create a domain object from the POSTed data (3) Put the new object on the session for later use by other servlets.
The details may differ, but many servlets will follow this general order of execution. This is a standard pattern that servlets which only implement doPost() follow.
req.getSession(true) is used because you can start the shopping cart (session) at any time.
14
public void doPost(req, resp) {resp.setContentType("text/html");HttpSession session = req.getSession(true);Order order = parseOrder(req);session.setAttribute("order",order);outputPostText(req, resp);
}
BookChoiceServlet
outputPostText( )parseOrder( )
doPost( )
Book choice servlet (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — In a real servlet you would have to catch and handle exceptions. This error detection and recovery has been left off of this example to shorten the code.
Additional information —
Transition statement — Next: Book Choice Servlet (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-29
Instructor Guide
Figure 16-14. Book Choice Servlet (2 of 2) RD8107.5
Notes:
This shows some of the details of the parseOrder() method. The example assumes that all of the parameters have valid values. The details by which line items are constructed from request parameters are not important to our example.
15
BookChoiceServlet
outputGetText( )outputPostText( )parseOrder( )
doGet( )doPost( )
public Order parseOrder
(HttpServletRequest req) {
Order order = new Order();
SaleLineItem line = null;
Enumeration enum =
req.getParameterNames();
while (enum.hasMoreElements()) {
String name = (String)
enum.nextElement();
String info = req.getParameter(name);
line = SaleLineItem.create(name, info);
if (line != null)
order.addLineItem(line);
}
return order;
}
Book choice servlet (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Credit Information Servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-31
Instructor Guide
Figure 16-15. Credit Information Servlet RD8107.5
Notes:
There is no error processing code shown on this page. Error handling would make the code more complicated, but it must be done. That is covered in depth in the section on controller design issues.
The flow shown here is very simple: Get saved data from the session and attach additional information to it before processing it (which could include getting the credit card approval, saving the order, sending it down the workflow, and so on).
req.getSession(false) is used here because it makes no sense to process an order if there is no preexisting shopping cart (session).
16
public void doPost(..) {
res.setContentType("text/html");
HttpSession session =
req.getSession(false);
if (session != null) {
Customer cust = parseCustomer(req);
Address addr = parseAddress(req);
cust.setAddress(addr);
Order order = (Order)
session.getAttribute("order");
order.setCustomer(cust);
processOrder(order);
outputPostText(out,order);
}
else { /* process error */ }
}
CreditInformationServlet
parseAddress( )outputPostText( )doPost( )
parseCustomer( )processOrder( )
Credit information servlet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Thread Safety
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-33
Instructor Guide
Figure 16-16. Thread Safety RD8107.5
Notes:
In general, access to a particular session object is handled by a single thread running on behalf of a single HttpRequest. In circumstances where this cannot be guaranteed, you should consider synchronizing access to the session object to avoid race conditions.
17
Thread safety� The HttpSession object is a shared resource
�Access to shared objects should be synchronized�Do not synchronize indirectly (for example, synchronizing
various servlets’ doPost() methods)�Instead, wrap sets of setAttribute() and getAttribute() in a
synchronized block
Customer cust = (Customer)
session.getAttribute("customer");
synchronized (cust) {
// work with the customer object
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — The session could be shared if the same client opens multiple browsers. It also depends on the browser.
Transition statement — Next: HttpSession Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-35
Instructor Guide
Figure 16-17. HttpSession Classes RD8107.5
Notes:
The key point of this slide is the HttpSessionBindingListener interface. Whenever an object is bound or unbound, it receives a notification through the interface if it implements that interface. This notice enables you to perform post-session processing, including permanently saving to a database data changes made during the session.
Unbinding happens if you programmatically unbind (by calling HttpSession.invalidate) or when timeout occurs. The timeout is configurable in the IBM WebSphere Application Server administration console, and is set to 30 minutes by default.
When unbinding occurs, it causes the representation of the session to be invalidated and removed from its context.
18
UserObject
HttpSessionBindingListener
valueBound(HttpSessionBindingEvent)valueUnbound(HttpSessionBindingEvent)
HttpServletRequestgetSession( )
HttpSessiongetAttribute(String)setAttribute(String,Object)removeAttribute(String)
<<interface>>
key : String
HttpSession classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — Basically, this allows an object to know when it is added or removed from a session.
Additional information —
Transition statement — Next: Session Serialization
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-37
Instructor Guide
Figure 16-18. Session Serialization RD8107.5
Notes:
Many application servers need to be able to serialize session objects. This may be to persist them to a data store or to pass them around between a cluster of servers. In any case, a general rule of thumb is to not store any object on the session object which is not Serializable.
IBM WebSphere Application Server supports distributed sessions by both session database persistence and session sharing across cluster members via memory-to-memory replication (A cluster is a set of replicated servers; a cluster member is an instance of a replicated server).
Within an application that is marked as distributable, all HTTP requests that are part of a HttpSession can only be handled on a single VM at any one time. In addition, objects placed into HttpSession objects via the setAttribute() method must implement the serializable interface. The web container may throw an IllegalArgumentException if a non-serializable object is placed into the session.
19
Session serialization� Objects stored in a session must be serializable:
�To share between servers in a clustered server configuration
�For persistence to work� Make sure that objects reachable from the session are also
serializable� When creating objects to be stored in the session, implement
the serializable interface as follows :
public class NewObject
implements java.io.Serializable {
...
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Servlet Objects (1 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-39
Instructor Guide
Figure 16-19. Servlet Objects (1 of 4) RD8107.5
Notes:
Assumptions:
• Sue and Bob are on different client systems
In this example, the two clients are running the same servlet.
Notice that different clients have different HttpSession objects. Since both servlets are Servlet A, they share the same ServletConfig. Also since they are also in the same Web Application, they share the same ServletContext.
Since they are different requests and thus different threads, they each have their own requests and responses.
20
Servlet A
Servlet AThread 1
Servlet AThread 2
ServletRequestHttpSessionServletResponse
ServletConfig
ServletResponseServletRequest
ServletContext
HttpSession
Client Bob
Client Sue
Servlet objects (1 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — You are revisiting the previous discussion of the servlets and associated objects. In this first example, both clients are running the same servlet (A). The second servlet (B) is used soon! The assumptions are the same for each situation, although not all conditions occur in each situation.
Additional information —
Transition statement — Next: Servlet Objects (2 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-41
Instructor Guide
Figure 16-20. Servlet Objects (2 of 4) RD8107.5
Notes:
In this example, the same client is invoking the same servlet (via two browser windows).
Note that two accesses by the same client (Sue) have the same HttpSession object. Since both servlet threads are for Servlet A, they share the same ServletConfig. In addition, since they are also in the same Web Application, they share the same ServletContext. Depending on how the browser is started (and what browser you are running), client Sue may in fact end up with multiple HttpSessions.
21
Servlet A
Servlet AThread 1
Servlet AThread 2
ServletRequestHttpSession ServletResponse
ServletConfig
ServletResponseServletRequest
ServletContext
Client Sue
Client Sue
Servlet objects (2 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Servlet Objects (3 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-43
Instructor Guide
Figure 16-21. Servlet Objects (3 of 4) RD8107.5
Notes:
Assumptions:
Sue and Bob are on different client systems.
Servlets A and B are in the same ServletContext.
Servlets A and B are running in the same JVM.
In this example, the two clients are running different servlets.
Notice that different clients have different HttpSession objects. Since they are running different servlets, they have different ServletConfig objects. Since both servlets are in the same Web Application, they share the same ServletContext.
22
Servlet A
Servlet B
ServletRequestHttpSession ServletResponse
ServletResponseServletRequestHttpSession
Client Bob
Client SueServletConfig
ServletContext
ServletConfig
Servlet objects (3 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Servlet Objects (4 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-45
Instructor Guide
Figure 16-22. Servlet Objects (4 of 4) RD8107.5
Notes:
Assumptions:
Servlets A and B are in the same ServletContext.
Servlets A and B are running in the same JVM.
In this example, the same client runs Servlet A and then runs Servlet B. You are not looking at the case where Sue is trying to run servlets A and B at the same time. The behavior of Sue running both A and B at the same time will vary from browser to browser, and the session accessed by B may or may not be the same one accessed by A.
Since it is the same client, the HttpSession object is shared between the two requests. Since they are running different servlets, they have different ServletConfig objects. Since both servlets are in the same Web Application, they share the same ServletContext.
23
Servlet A
Servlet B
ServletRequestHttpSession ServletResponse
ServletConfig
ServletResponseServletRequest
ServletContext
Client Sue
Client Sue
ServletConfig
Servlet objects (4 of 4)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: WebSphere Extensions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-47
Instructor Guide
Figure 16-23. WebSphere Extensions RD8107.5
Notes:
getUserName() is tied into the security framework so that if a challenge dialog has already been issued and the user has provided a user name, it is returned. If no challenge has been issued, it returns the String anonymous.
There is a configurable in-memory session pool size for WebSphere Application Server. If this size is exceeded (and this pool size is hard limited), new sessions are created, but they are invalid and not saved in any way (deleted at request end). Invalid sessions can be detected by sending the isOverflow() method to the session.
The sync() method is used to commit session data to the shared repository prior to the servlet's service() method completing.
24
WebSphere extensions� WebSphere provides an extension to HttpSession in the
interface: com.ibm.servlet.websphere.servlet.session.IBMSession�This extends HttpSession for session support and
increased Web administrators' control in a session cluster environment
� Has the following additional methods:�public String getUserName() – identifies the
authenticated owner of the session�public boolean isOverflow() – determines if the session is
valid when hard limits are set on the session manager�public void sync() – used to perform an early commit on
session transaction� WebSphere extensions are not portable across Java EE
application servers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-49
Instructor Guide
Figure 16-24. Checkpoint RD8107.5
Notes:
Write down your answers here:
25
Checkpoint1. Explain how to invalidate a session.2. Why do you need to be concerned with thread safety?3. Why would you need to serialize a session?4. What are the WebSphere extensions to the HttpSession
interface?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
26
Checkpoint solutions1. A session is invalidated by being inactive too long, by being
explicitly invalidated (HttpSession's invalidate() method), or when the client browser closes (if a cookie is being used to manage the session).
2. If multiple browsers within the same client are sharing the same session, getting/setting the attributes should be synchronized.
3. If the successive requests within the same session execute on different servers/JVMs, the session object and attributes may need to be serialized to be moved among the different servers.
4. sync(), getUserName(), isOverflow()
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-51
Instructor Guide
Figure 16-25. Unit summary RD8107.5
Notes:
27
Unit summary� Having completed this unit, you are able to:
�Discuss the task of managing client application data � Session management with the WebSphere Application Server
Session Manager tool�Describe the use of HttpSession to maintain a user
session�Explain how object sharing is implemented in the servlet
environment�Describe the various ways to manage application state
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 16. HttpSession: Management of Application Data 16-53
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
16-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 17. URL RewritingEstimated time
00:20
What this unit is about
In this topic you learn how your servlets can use URL encoding for session management. The key here is that all references to URLs must be encoded to include the session ID. This also means that any Web pages you access must be dynamically generated, or you lose your session.
What you should be able to do
After completing this unit, you should be able to:
• Describe what URL rewriting is used for
• Describe the use of URL rewriting for session management
• Explain when to use URL rewriting
How you will check your progress
Accountability:
• Checkpoint
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-1
Instructor Guide
Figure 17-1. Unit objectives RD8107.5
Notes:
The purpose of this topic is to become familiar with URL rewriting and when to use it.
2
Unit objectivesAfter completing this unit, you should be able to:
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Look at what will be covered in this topic.
Details — If cookies cannot be used for session management support (HTTPSession), you will have to use URL encoding to support the session.
Additional information — If students want to know how to configure the Server Tools to use URL encoding, they can look in the online help for Application Developer. Similar information appears in these instructor notes in a few pages.
Transition statement — Look at what URL encoding is.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-3
Instructor Guide
Figure 17-2. URL Rewriting (1 of 2) RD8107.5
Notes:
3
URL rewriting (1 of 2)� Is always an available option of session tracking� May be used by the server to establish tracking session data
where a client does not accept a cookie� Involves adding data to the URL path that can be interpreted
by the server on the next request, to associate the request with a session
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Look at why you need URL encoding.
Details —
Additional information — Any URLs you write out have to include the session ID. This would include any href links in your HTML output as well as any redirections from your servlet. This is a consideration when you build dynamic HTML pages.
Transition statement — Look at how the API helps you to do this.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-5
Instructor Guide
Figure 17-3. URL Rewriting (2 of 2) RD8107.5
Notes:
When you use URL rewriting, you call methods that, when necessary, include the session ID in a link. You must call these methods for every link in the servlet response.
The session identifier can be passed as a parameter on any link or form the user may submit from the page, for example,
<a href=”/store/catalog;jsessionid=BEF112QAAAAACWQAAAASYIA”>catalog</a>
In this example, when the user clicks this link to move to the store/catalog page, the session identifier passes into the request as a parameter.
4
URL rewriting (2 of 2)� URL encoding for session ID passing
�Requires the developer to:� Use special encoding APIs� Set up the site page flow to avoid losing the encoded information
� Limits the flow of site pages exclusively to dynamically generated pages (such as pages generated by servlets or JSP pages)
� Works by actually storing the session identifier in the page returned to the user
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — APIs to do the encoding and limitations on your Web site.
Details — There are special methods you will call to encode any hrefs or for doing redirections. You can do these in your code even if you are NOT using URL encoding. If your HttpSessionobjects are using cookies, the encode methods do nothing. If you are using URL encoding with your sessions, the encode methods add the appropriate session ID support needed with URL encoding.
Now whenever you navigate to new Web pages, the session ID must be included in the new Web page. This, in effect, forces you to have dynamic Web pages for all of your Web pages.
Additional information —
Transition statement — Look at a coding example.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-7
Instructor Guide
Figure 17-4. Servlet Code RD8107.5
Notes:
The encodeURL() and sendRedirect() methods decide whether the URL needs to be rewritten, and return the URL either changed or unchanged. The rules for URLs and redirected URLS are somewhat different, but in general, if the server detects that the browser supports cookies, then the URL is not rewritten.
If encoding is being done, the first example above would generate code similar to the following:
<a href=”/store/catalog;jsessionid=BEF112QAAAAACWQAAAASYIA”>catalog</a>
5
Servlet code� If the servlet returns HTML directly to the requester (without
using a JSP page), the servlet calls the encodeURL() method to encode the session ID�This method associates a session ID with a URL
out.println("<a href=\"");
out.println(response.encodeURL ("/store/catalog"));
out.println("\">catalog</a>");
� Even pages using redirection (a common practice with servlet-JSP combinations) must encode the session ID as part of the redirect:
response.sendRedirect(response.encodeRedirectURL(
"http://myhost/store/catalog"));
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Look at the URL encoding APIs.
Details — Note that the student notes contain the sample output from a encodeURL()call. If you forget to do this, you lose your session.
Additional information — Some of your students may want to change the session support to turn on URL encoding. They need to do the following:
Use the Administrative Console of WebSphere Application Server, and expand the tree: Servers Application Servers <server name> Web Container Session management. Check the Enable URL rewriting box, and then save your configuration.
Once the configuration has been updated, you get the new options the next time the application server is started (either outside or inside of Application Developer).
Transition statement — JSP pages have to do the same thing.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-9
Instructor Guide
Figure 17-5. JSP Code RD8107.5
Notes:
6
JSP code� When JSP pages use URL encoding, the JSP page calls the
encodeURL() and encodeRedirectURL() methods to encode the session ID:
response.sendRedirect(response.encodeRedirectURL(
"http://myhost/store/catalog"));
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — JSP pages have to call encodeURL() andencodeRedirectURL() for their references and redirections.
Details — This support is NOT automatic and must be coded by the JSP developer.
Additional information —
Transition statement — Look as some more details of URL encoding.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-11
Instructor Guide
Figure 17-6. URL Rewriting and Cookies RD8107.5
Notes:
If the user's session is lost, the servlet contacted through that link creates a new session, but the new session does not have the data associated with the previous session. Once a servlet loses the session data, the data is lost for all servlets that share the session.
7
URL rewriting and cookies� If the user clicks a link with a rewritten URL:
�The Web container recognizes and extracts the session ID �The getSession() method uses the session ID to get the
user's HttpSession object� If the user's browser does not support cookies and the user clicks
an unrewritten URL:�The user's session is lost
� You should consistently use URL rewriting if your servlet is to support clients that do not support or accept cookies
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Once again, point out what happens if even one link isn't coded correctly.
Details — If your code does not support URL encoding by calling the encodeURL()method for ALL links, you will lose your session - forever.
Additional information —
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-13
Instructor Guide
Figure 17-7. Checkpoint RD8107.5
Notes:
Write down your answers here:
8
Checkpoint1. What is URL rewriting?2. When would you use URL rewriting instead of cookies?3. What is the danger if the user's browser does not support
cookies, and the user clicks a URL that has not been rewritten?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
9
Checkpoint solutions1. It is a technique for maintaining the session ID across
browser interactions. Essentially, the session ID is sent as part of the URL sent to the server.
2. If it is essential to your application that a session be maintained, you need to use URL rewriting. Otherwise, the client could disable cookies on his or her browser, and you would lose the session ID, and hence the session.
3. In this case, the URL sent back to the server would not contain the session ID, and there would be no cookie containing the ID either. The session would then be lost.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-15
Instructor Guide
Figure 17-8. Unit summary RD8107.5
Notes:
10
Unit summary� Having completed this unit, you are able to:
�Use URL rewriting to pass the session ID�Determine when URL rewriting is appropriate
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 17. URL Rewriting 17-17
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
17-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 18. Best Practices for Session ManagementEstimated time
00:25
What this unit is about
Since servlets and JSP pages are stateless, any application state specific to a user must be stored outside the servlet (or JSP page). This information is called session state.
Determining what to do with this session state is one of the most challenging problems in servlet programming.
In this unit you discuss a number of approaches to managing this session state and their pros and cons.
What you should be able to do
After completing this unit, you should be able to:
• Identify issues related to sessions
• Examine options for session management
• Identify advantages and disadvantages of each option
• Examine special concerns with cluster configurations
• Identify techniques for using sessions efficiently
How you will check your progress
Accountability:
• Checkpoint • Discussion
References
http://www.ibm.com/developerworks/websphere/library/bestpractices/store_objects_in_httpsession.html Best Practice: Storing objects in HTTP sessions
http://www.ibm.com/developerworks/websphere/library/bestpractices/httpsession_performance_serialization.html
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-1
Instructor Guide
Best Practice: Improving HttpSession Performance with Smart Serialization
http://www.ibm.com/developerworks/websphere/library/bestpractices/not_creating_httpsessions_in_jsps.html Best Practice: Not creating HttpSessions in JSPs by default
http://www.ibm.com/developerworks/websphere/library/bestpractices/ releasing_and_invalidating_httpsessions.html Best Practice: Releasing and invalidating HTTP sessions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Examine options for session management�Identify the advantages and disadvantages of each option�Examine special concerns with cluster configurations�Identify techniques for using sessions efficiently
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-3
Instructor Guide
Instructor notes:
Purpose — In this topic you discuss several approaches to session data management.
Details — When you talk about session data management, you are not just talking about using the HttpSession object. The use of HttpSessionis just ONE way available to developers when trying to manage session data. Make sure your students understand you are talking about more than just HttpSessionin this topic.
Additional information —
Transition statement — Look again at why you need to worry about session data when designing and implementing your servlets and JSP pages.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-2. Session Strategies - Review RD8107.5
Notes:
In a previous unit, you discussed the major issues concerning session storage and identified the two approaches to session management as being client-based and server-based. You now look at several technologies used in the client-side and server-side approaches, and identify their advantages and disadvantages in addressing session storage issues.
3
�Session state can be stored on either the client or the server
�You examine several session management strategies and figure out where each applies
�Cookies�Hidden Fields�URL Rewriting
�Store state in a database�WebSphere Application Server Distributed Sessions�WebSphere Application Server Session Affinity
Client Side
Server Side
Session strategies: review
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-5
Instructor Guide
Instructor notes:
Purpose — Bridge between the overview and the detailed discussion.
Details — You've talked about session state storage issues and the two general approaches of storing session data in the client and saving it in the server. You have also discussed cookies, HTTP Session, and URL Rewriting in detail. You examine the techniques in summary, including their pros and cons.
Additional information —
Transition statement — First, look at cookies.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-3. Cookies for Session State (1 of 2) RD8107.5
Notes:
Some application data may not be appropriate for storage in cookies.
Cookies are data maintained on the client by the browser on behalf of the server. Cookies can be made to persist within or across browser sessions.
Cookies are the preferred way to pass an HttpSession ID, if any, to the Web application server. The same approach can be used for other data that is constant across the Web application. For example, in an online buying application it might make sense to store the customer ID in a cookie to eliminate having to use URL encoding or hidden fields.
Cookies are an excellent way to store a small amount of user preference data. For example, it may be desirable to tailor the ProductCatalog list by Customer based on the past history of visits to the site. In this case, you might maintain a persistent cookie with the last query used to select products.
4
Cookies for session state (1 of 2)� Advantages
�Unique to a client machine�Easy to use
� Automatically passed in the header� Does not require explicitly coding hidden fields or URL query strings in
the HTML and JSP pages� Makes the application much simpler to develop, test, and maintain
�Range of lifetimes� Disadvantages
�Can be turned off� May need to use URL rewriting
�Not secure�Limit of 4096 bytes per cookie
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Material for discussion on cookies' pros and cons:
Pros:
The ability to maintain persistent cookies means that the client machines can be enlisted to help share the cost of running the application. In an e-business application with millions of users, not having to maintain often used preference data for each one can be a significant savings in both space needed to store it and time needed to retrieve it.
Cons:
Passing cookies back and forth can be relatively expensive.
Another problem is that not all browsers or levels of browsers support cookies. Even if they are supported, users can turn cookies off as a security or privacy measure, which means that either:
Your Web application needs to be coded for the case where cookies are not available, and use alternative techniques (discussed below); or,
You must make an explicit decision to support only users with browsers having cookies enabled. Also, other HTTP-based clients, such as applets, may have trouble dealing with cookies, restricting the servlets that they may invoke.
Alternatives:
URL encoding techniques can be used to put the equivalent data in the URL query string, rather than relying on cookies.
Transition statement — Next: Cookies for Session State (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-4. Cookies for Session State (2 of 2) RD8107.5
Notes:
Since cookies are limited to 4096 bytes of data, larger strings must be split over multiple cookies, which becomes a challenging programming proposition.
5
Cookies for session state (2 of 2)� Conclusion:
�Use cookies only for small data sets that are not secure �You may need a backup plan for situations where cookies
are disabled
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Hidden Fields
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-5. Hidden Fields RD8107.5
Notes:
This mechanism was the default in the early days of Web development.
Hidden fields have no UI representation, and so cannot be changed by the browser user. The idea is that this is something that has a value set on a Web page and which a servlet can read.
6
Hidden fields� HTML includes a way to embed non-displayable information in
an INPUT tag�Allows information from previous interactions to be carried
through to a new form:<INPUT NAME=“CustomerAcct”
TYPE=“HIDDEN” VALUE=“12345678”>
� Hidden fields are read back like any other field.�Use req.getParameter(String)
� where req is an instance of HttpServletRequest� Hidden fields are stored on the client, in the HTML page itself
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Hidden Fields for Session State (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-6. Hidden Fields for Session State (1 of 2) RD8107.5
Notes:
Hidden fields are retransmitted back to the server on a POST or GET request as part of the HTTP request. Since they are sent with the HTTP request each time, they can be used by whatever servlet receives that request, regardless of the server it is running on. In other words, all the information needed by each servlet that was originally created by a previous servlet will be carried along with the HTTP request.
On many browsers, hidden fields can be seen via the browser's view page source option.
7
Hidden fields for session state (1 of 2)� Advantages
�Unique to each client�Can handle larger data than cookies�Cannot be turned off�Relatively simple�Server independence while maintaining session data
� Disadvantages�Security can be compromised (can be spoofed)�Not secure under HTTP�Data is always transferred both ways, increasing network
traffic and potentially impacting performance�Not supported by a framework like HttpSession�Only works with dynamically generated forms�Text only
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-13
Instructor Guide
Instructor notes:
Purpose —
Details — If multiple browser windows are open, the hidden fields are unique to each browser window.
Additional information —
Transition statement — Next: Hidden Fields for Session State (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-7. Hidden Fields for Session State (2 of 2) RD8107.5
Notes:
8
Hidden fields for session state (2 of 2)� Conclusion:
�Useful for medium-size data sets�Useful in a cluster configuration
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Session Storage Options
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-8. Session Storage Options RD8107.5
Notes:
Sometimes the complexity or sheer size of session data makes it difficult or impossible to store in hidden fields, cookies, or other client-side storage mechanisms. Other considerations may also make it necessary, or desirable, to keep data behind the firewall (for instance, security). In these cases, it is preferable to store the data in a middle-tier persistent store.
There are two ways to persist session data to a database: using Enterprise JavaBeans, and writing directly to the database.
Other solutions (like a serialized object file) may be reasonable for low-volume applications where reliability is not as crucial.
The most common approach to identifying those records in the middle-tier database that correspond to a particular client is to store a simple key in a hidden field or a client-side cookie with a unique identifier that can be used to associate them.
9
� In most cases, you want to store session information in a datastore� Allows the use of session clustering
WebSphere Application Server
WebSphere Application Server
Browser
Datastore
Session storage options
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — With Edge Server, the session data is cached in memory. A copy is also stored in a database for availability after a server switch.
Transition statement — Next: WebSphere Distributed Sessions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-9. WebSphere Distributed Sessions RD8107.5
Notes:
The client side solutions for storing session data met the goal of server independence, but have definite limitations in size and type of data stored, scalability, and spoof-ability. You can use a content-based routing scheme or store the session data in a database to meet the goal of server independence, but you need to establish a session management framework to use in your application to do that. Factoring failover support makes the task even more complicated. On the other hand, you can use the Session Tracking API framework (HttpSession) support in WebSphere Application Server.
WebSphere Application Server provides support for storing session data (HttpSession) locally or in a clustered environment to obtain the goal of server independence. The data can be stored in a database or in other servers’ memory. By default, the application server is configured to save session data on a single server in memory. The distributed environment setup is available through the administration console: Servers Applications Servers <server name> Session Management (under Container Settings) Distributed Environment Settings. Redbooks SG24-7304 (WebSphere Application Server V6.1 System Management & Configuration) and SG24-7305 (WebSphere Application Server V6.1:
10
WebSphere distributed sessions� WebSphere Application Server supports HttpSession in a
clustered server environment with failover� Session information can be externally stored in:
�Database persistent sessions�Memory-to-memory persistent sessions
� Session attributes should be serializable� Session data is cached at the server level
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-19
Instructor Guide
Planning and Design) are good sources for additional configuration management information concerning distributed sessions.
Storing session states in an external store provides a degree of fault tolerance. If an application server goes offline, the state of its current sessions is still available in the external store. This availability enables other application servers to continue processing subsequent client requests associated with that session.
All the attributes set in a session must implement java.io.Serializable if the session requires external storage.
Saving session states to an external location does not completely guarantee their preservation in the case of a server failure. For example, if a server fails while it is modifying the state of a session, some information is lost and subsequent processing using that session can be affected. However, this situation represents a very small period of time when there is a risk of losing session information.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — To emphasize that the requirements to effectively use session state in cluster environments are met by built-in features of WebSphere Application Server within the framework of the Session Tracking API (HttpSession).
Details —
Additional information —
Transition statement — Next: WebSphere Application Server Session Affinity
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-21
Instructor Guide
Figure 18-10. WebSphere Application Server Session Affinity RD8107.5
Notes:
Session affinity provides conformance to the Servlet 2.4 specification which states that multiple requests for a session cannot coexist in multiple application servers. Of course, this rule no longer applies when the server is not available; at that point recovery can occur by using the distributed sessions support (if it is enabled).
Session affinity provides server independence and attendant benefits such as load balancing; although the session must continue to be used on the server where it was established, the choice of that server to handle the initial request is not restricted to a particular server.
Session affinity information (such as the identifier of the cluster member) is maintained along with the session id information by either URL rewriting or cookies, as specified in configuration of the plug-in.
11
WebSphere application server session affinity� Servlet API 2.5 requires HttpSession objects to be:
�Accessible only to the Web application that created the session
�Handled by a single JVM per application at any one time� Session affinity provides this capability in a cluster
environment � Implemented via the WebSphere Web Server plug-in� Operation:
�First request of a session selects the server on a round-robin basis
�Subsequent requests for that session go to the assigned server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Explains how the Servlet 2.4 specification's constraints regarding HttpSessionaffinity is handled in a clustered environment.
Details —
Additional information —
Transition statement — Next: Using HttpSession Objects Efficiently
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-23
Instructor Guide
Figure 18-11. Using HttpSession Objects Efficiently RD8107.5
Notes:
.
Don't store large object graphs in HttpSession. From a performance point of view you probably want to limit the amount of information you put into the HttpSession to about 2 KB to 4 KB.
With WebSphere Application Server there are limits to the amount of information you can put into the persistent session, but you hit performance problems before you reach the physical limits of 32 KB to 2 MB (the limits depend on the database you are using).
In some applications, each servlet may only require a fraction of the total session data. As an alternative to storing the an entire object graph in the HttpSession, use JDBC or EJBs to partition and maintain the state data needed by each servlet in the application. The session data could then contain keys to point to the state data.
Performance tests have shown that specifying session=“false” for a JSP page can save 5% in throughput processing by avoiding unnecessary work. This is a significant savings for a simple coding change.
12
Using HttpSession objects efficiently� Minimize the number and size of attribute objects� Provide a logout function to invalidate session
�session.invalidate()
� Remove attributes from the session when they are no longer required�session.removeAttribute(String name)
� Set the JSP page directive session attribute to false when appropriate�<%@ page session=“false” %>
�This indicates that the page does not participate in the user session
�Implicit session variable is not available� Use a reasonable session timeout value
�Balance user convenience versus resource consumption�Can be set in Web Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
The session timeout value can be set for the Web application via the <session-timeout> element in web.xml or in the Session timeout field of the Overview tab in Application Developer 's Web deployment descriptor editor. The timeout can also be set on a per session basis with the setMaxInactiveInterval() method and queried with getMaxInactiveInterval(). Setting a reasonable timeout value also can enhance security by limiting the vulnerability time if a user forgets to logout.Note: the session timeout value is specified in minutes in the deployment descriptor and in seconds in the setMaxInactiveInterval() method. The default timeout value can also be set in the application server configuration. WebSphere Application Server v6.1 has a default timeout of 30 minutes.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: WebSphere Sessions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-12. WebSphere Sessions RD8107.5
Notes:
When an application is using a session, the LastAccess time field is updated any time data is read or written to that session. If persistent sessions are being used, this produces a new write to the database. This performance hit can be avoided by using a manual update and having the record written back to the database only when data values are updated, instead of each read or write of the record. To use manual update, it must be enabled in the session manager, and the application code must use the com.ibm.Websphere.servlet.session.IBMSession instead of the generic HttpSession class. This impacts portability, however.
13
WebSphere sessions� Each session access is a transaction in the database
�Begins at getSession, ends at the end of the servicemethod
�Can choose to end prematurely with sync� This writes the data in the session object to the database� Improves performance: session persists only when necessary� IBMSession session = (IBMSession)request.getSession(false);
// ...
customer = (Customer)
session.getAttribute(CommandConstants.CUSTOMER);
// ...
// code that updates the customer goes here
// ...
session.sync;
// ...
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: WebSphere Administration Issues
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-13. WebSphere Administration Issues RD8107.5
Notes:
When setting up shared sessions, your administrators have to take these issues into consideration.
If the session data is NOT in memory, then the initial hit to load the cache from the database can be substantial. Your administrators can set up back-end parallel databases for reliability.
14
WebSphere administration issues� Use cached session data
�When the session data is already in memory, the performance improvements are as great as 50%
� Configure maximum number of sessions�Helps manage the use of server resources
� Use a dedicated database for the session database�Avoids contention for JDBC connections�Improves performance
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-29
Instructor Guide
Instructor notes:
Purpose — Discuss some of the configuration issues in WebSphere Application Server.
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-14. Checkpoint RD8107.5
Notes:
Write down your answers here:
15
Checkpoint1. Name some of the advantages and disadvantages of using
cookies, hidden fields, and HttpSession for session management
2. When would you need to store session data to a database?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
16
Checkpoint solutions1. Cookies
• Pro: easy to use, stored on each client machine• Con: can be turned off, unsecure, limited in size.Hidden fields• Pro: stored on client, cannot be turned off, easy to retrieve, can
be larger than cookies• Con: unsecure, transmitted both ways, must be generated
dynamically.HttpSession• Pro: stored on server, secure, supported by Servlet API;• Con: can be a problem when sharing across servers,
maintaining session ID can be problematic (cookies, URL rewriting), can get quite large.
2. If you expect that a session started on one server may be switched to another server, and you are using session data to maintain state, you want to make that data available to any server by storing it in a database.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 18-15. Unit summary RD8107.5
Notes:
17
Unit summary� Having completed this unit, you are able to:
�Examine options for session management�Identify the advantages and disadvantages of each option�Examine special concerns with cluster configurations�Identify techniques for using sessions efficiently
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 18. Best Practices for Session Management 18-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
18-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 19. JavaBeans and the Model-View-Controller PatternEstimated time
00:35
What this unit is about
In this unit you learn about the JavaBeans specification from Sun. The JavaBeans specification allows you to write reusable software components that can be used with development tools such as Rational Application Developer. You will also see that JavaBeans are an integral part of developing well-designed Web-based systems.
You will also look at the model-view-controller (MVC) design model. The MVC design is a very common object-oriented design, and is applicable to GUI applications and Web applications that use servlets and JSP pages.
The MVC design allows you to make full use of servlets, JavaBeans, and JSPs.
What you should be able to do
After completing this unit, you should be able to:
• Explain the uses of JavaBeans
• Understand the JavaBeans component model
• Explain JavaBean properties
• Describe the model-view-controller (MVC) design pattern and its benefits
• Identify the components that make up the model, view, and controller
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-1
Instructor Guide
References
http://java.sun.com/products/javabeans/docs/spec.html JavaBeans Specification Version 1.01
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-1. Unit objectives RD8107.5
Notes:
Rational Application Developer uses the JavaBeans architecture for its component model.
2
Unit objectives� After completing this unit, you will be able to:
� Explain the uses of JavaBeans� Describe the JavaBeans component model� Explain JavaBean properties� Describe the model-view-controller (MVC) design pattern
and its benefits� Identify the components that make up the model, view, and
controller
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-3
Instructor Guide
Instructor notes:
Purpose — This unit talks about the JavaBean specification from Sun. Students need to understand beans so that they can understand and take advantage of the JSP useBeantag.
Details —
Additional information —
Transition statement — Look at what JavaBeans are.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-2. What Are JavaBeans? RD8107.5
Notes:
You've probably heard the term beans many times in regard to Java, but what really is a bean? The following defines the relevant terms.
JavaBeans is Java's implementation and specification of a software component model. (component model is defined shortly). JavaBeans is also used when referring to the technology.
What a developer builds is called a JavaBean, or more commonly, a bean.
Since a bean is written entirely in Java, a developer building a bean is still coding in Java, along with all of Java's benefits. When you're coding server-side applications, platform neutrality is one of the key benefits.
JavaBeans also provide a convenient “wrapping” for data objects. Since the interface to a bean is well understood, and a description of it is available at run-time, beans can be accessed by applications that are only loosely coupled with the beans they access. We will see later how this property of beans is used in JSP technology to access data created by servlets and back-end business objects.
3
JavaBeans Java's software component model specificationA reference to the technology
JavaBean/Bean A reference to a component built accordingto the JavaBeans specification
What are JavaBeans?
Component Packaged software object
with standardized interfaceReusable in multiple applications
Component Architecture
A set of specifications that details howcomponents interact with each otherand with other software tools
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-5
Instructor Guide
JavaBeans and Enterprise JavaBeans (EJBs) are two different architectures. An Enterprise JavaBean is not actually a JavaBean, in the meaning of the architecture we discuss in this unit.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-7
Instructor Guide
Figure 19-3. Characteristics of a JavaBean RD8107.5
Notes:
You have been learning about beans so far without seeing where you might use them in your application development. Besides the advantage of having a packaged component available in a library, with a standardized interface, there are others.
JSP technology leverages JavaBeans. You can directly relate HTTP input parameters to a bean's parameters. Also, a bean van be used to pass results from a servlet to the JSP page.
Additionally, if you use the IBM Common Connector Framework (CCF) to connect to Enterprise Information Systems like CICS or IMS, you can take advantage of JavaBeans as well. The J2EE Connector Architecture (variously called J2C and JCA) is the Java-wide implementation of a connector framework for accessing enterprise systems.
4
Characteristics of a JavaBean� Written in Java� Also a standard Java class or instance� Adheres to the Sun JavaBeans specification:
�Has a set of public features� Properties, methods, and events
�Requires a zero-argument constructor�Implements the Serializable interface
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: A Simple Property
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-9
Instructor Guide
Figure 19-4. Why Use Beans? RD8107.5
Notes:
We've been talking about beans so far without mentioning where you might use them in your application development. Besides the advantage of having a packaged component available in a library, with a standardized interface, there are others.
One of the earliest uses of beans was for visual programming in Java-based integrated development environments, or IDEs. Since the IDE knows how beans are defined, the tools can dynamically interrogate a bean to determine its interface, or set of features. Our example shows a window with a text field and a button. Next to the window is an OrderManager bean. This bean is not visible to the user of the window, but is used for the application functionality. In this visual programming example, the invisible OrderManager bean is available to the developer for visual programming. Note the green (in the visual) arrow from the button to the OrderManager bean. This indicates that when the Button bean is clicked, which generates an actionPerformed event, the queryOrder method will be invoked. The developer created this connection by selecting the actionPerformed event feature of the button and the queryOrder method feature of the OrderManager bean. Application Developer generates the underlying Java code to support this connection. Note that the queryOrder method requires a parameter, the order number.
5
Why use beans?� Visual Programming Tools that provide a reliable
, standardized encapsulation model� JSP Pages
<jsp:useBean id="order" scope="request" ... />…
<jsp:getProperty name="order" property="customer" />
� Java EE Connectors
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Another connection is used to pass this parameter. The developer connected the text property feature of the TextField bean to the number property of the connection itself. Since the queryOrder method needed a parameter, Application Developer automatically made it a property of the connection. Again, the tool generates the underlying Java code to make this work.With the advent of JSPs, another use of beans became available. One now could directly relate HTTP input parameters to a bean's parameters. Also, a bean could be used to pass results from a servlet to the JSP.
Additionally, if you use the IBM Common Connector Framework (CCF) to connect to Enterprise Information Systems like CICS or IMS, you can take advantage of JavaBeans as well. J2EE Connectors is the Java-wide implementation of a connector framework for accessing enterprise systems; it is based on the IBM CCF.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-5. A Simple Property RD8107.5
Notes:
6
name� Property example:
name, of type String
� Connecting and using a property appearsto be a violation of encapsulation
� Properties are exposed through standardgetter and setter signatures:
–public void setName(String aName);–public String getName;
� name is of Simple property type
A simple property
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-6. JavaBean Property Types RD8107.5
Notes:
JavaBeans technology also supports bound and constrained properties. When a bound property is changed, the change is reported (via a PropertyChangeListener) to other components that have registered an interest in the property. The same things happen with constrained properties, but in this case a VetoableChangeListener is used, and the listening component gets the opportunity to veto the change. Bound and constrained properties are primarily of interest when using visual JavaBeans (for instance, a canvas component might veto a change to a drawing component if the change would cause the drawing component to become too big for the canvas).
7
Properties Methods Events
Attributes that can be read and/or modified Behaviors of the bean
Changes of state that a bean can signal to interested parties
Types: Simple, Indexed, Boolean
� Simple: A single readable or writeable property� Boolean: A simple property that is a Boolean� Indexed: A property that is an array of values
JavaBean property types
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Boolean Properties
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-7. Boolean Properties RD8107.5
Notes:
8
Boolean properties� Boolean Properties can have a getter of the form:
�public boolean is<PropertyName>();� Example:
�Property is manager of type boolean�Getter method is public boolean isManager()�Setter method is public void setManager(boolean)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-8. JavaBean Naming Conventions RD8107.5
Notes:
JavaBean method names and signatures conform to standard conventions in order to facilitate introspection.
Rational Application Developer generates code that fully conforms to these conventions. Therefore, a proper get and set method is generated for each property.
It is possible to override these conventions, and to explicitly provide additional information, through the use of an auxiliary object called a BeanInfo object, but discussion of this is beyond the scope of this class.
9
� The JavaBean specification includes rules and conventions used for the naming and type signatures of access methods
– Useful documentation hint for human programmers– Enable the development of tools that recognize design
patterns, and use them to analyze and understand components
� Conventions can be thought of as the implicit specification of a bean's exposed properties
public String getName()public void setName(String aName)
Readable/Writeable propertyname of type String
JavaBean naming conventions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 19-9. Model – View – Controller RD8107.5
Notes:
The book Design Patterns by Gamma, Helm, Johnson and Vlissides, captures reusable designs, not code. For each design, it lists the pros and cons so you can make designs with your eyes open. In the Introduction, they discuss the model-view-controller (MVC) design approach popularized in Smalltalk-80. In this design, you separate the GUI, or presentation, from the model via an intermediary controller. It is also common, and desirable, to separate the business logic from the infrastructure support (security, communications, database, and so forth). This separation makes it easier to extend or maintain an application. It is easier because the changes are more encapsulated to one area of the system. The MVC approach itself is composed of several design patterns like Observers and Composite.
Although MVC was originally implemented in Smalltalk, the design patterns used apply to any language. Hence, MVC is a pattern that can and is used in Java. This design pattern is encouraged when using Rational Application Developer.
10
Model – view – controller� The model
�Is singular (there is only one)�Implements the problem domain�Handles ALL of the business logic
� The view�Can be one of many�Is a window into the model�Only provides presentation and user manipulation
� The controller�Can be one or many, depends on application architecture�Determines the user request�Parses input parameters�Invokes appropriate business beans
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-21
Instructor Guide
Not only can patterns be used across languages, but also across technologies. The view could be implemented as a Web page, the controller as a servlet, and the model as JavaBeans or Enterprise JavaBeans (EJBs).
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-23
Instructor Guide
Figure 19-10. MVC in J2EE (Server-side Programming) RD8107.5
Notes:
The participants in this structure are:
Servlet: A given request either gathers data needed for the display of a given state or invokes the action causing a transition out of the state. This responsibility makes it the controller in a model-view-controller (MVC)-based application.
JSP pages: Handle the generation of HTML code for a given request result, representing the view. The JSP pages' access to the model is for retrieving any results of the business processes (model). JSP technology is not limited to HTML; you can also think of other view components such as JSP tags and XML with XSL.
JavaBeans: The wrapper which encapsulates the access to the enterprise business logic (that is, back-end data and function). This function makes the wrapper the model in the MVC pattern, and can be represented by JavaBeans, Enterprise JavaBeans, or both.
HTML: Handles the static content of the display.
11
�View–HTML tags–JSP tags–XML and XSL
�Model–InventoryManager–InventoryItem–ShipmentReceived
�Controller–Servlet
Servlet
Database
JSP Page
Browser
JavaBeans
Results JavaBean
MVC in Java EE (server-side programming)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-25
Instructor Guide
Figure 19-11. Benefits of MVC Design Pattern RD8107.5
Notes:
One of the benefits of the model-view design pattern is that you can have better parallel development. You can divide your application into three fairly distinct sections, each requiring different skills, allowing you to better manage your development cycle and team.
Another benefit is the ability to react to changes faster, since modifications can be made to smaller pieces of code that are loosely coupled, not tightly coupled.
Don't forget that visual beans and non-visual beans need to communicate. The visual bean is a window into the model. It can't display something that is not in the model.
Having many small components makes it easier to reuse them. If a bean is too big and complex, it is probably not general and easy enough to reuse.
12
Benefits of MVC design pattern� Parallel development
�Work on model and view-controller at the same time� Project management challenge
�GUI bean developers need to talk to Invisible bean developers
� Smaller components imply better chance for reuse� Ability to react to changes:
�Can change the user interface without impacting business logic( for example, change the text field to a list of choices)
�Can change the business logic without impacting the UI( for example, tax laws change every year, but UI is still amount owed or refunded)
�Can move location of data without impacting the UI or business logic( for example, migrate from test system to production)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-27
Instructor Guide
Figure 19-12. Checkpoint RD8107.5
Notes:
Write down your answers here:
13
Checkpoint1. Why does a JavaBean component require a zero-argument
constructor?2. What are the benefits to an MVC design?3. Specify the components of the model, view, and controller.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
14
Checkpoint solutions1. The JavaBean framework instantiates a JavaBean using
the zero-argument constructor.2. Groups of developers can be working on different areas of
the application. Each group can develop and test at their own pace, but in parallel. With pre-built components that are focused on a specific responsibility (perhaps representing an invoice or customer), it is much easier to reuse these components in other applications. Because Web applications frequently change their look, having the view coded separately makes it much easier to update.
3. The one model comprises the business classes. The many views are typically different GUI ways to access the model. The many controllers take the requests from the GUIs and invoke the proper part of the model.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-29
Instructor Guide
Figure 19-13. Unit summary RD8107.5
Notes:
15
Unit summary� Having completed this unit, you are able to:
� Explain the uses of JavaBeans� Describe the JavaBeans component model� Explain JavaBean properties� Describe the model-view-controller (MVC) design pattern
and its benefits� Identify the components that make up the model, view, and
controller
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 19. JavaBeans and the Model-View-Controller Pattern 19-31
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
19-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 20. JavaServer Pages with JavaBeansEstimated time
00:20
What this unit is about
When using the model-view-controller design, the JSP is the view. The dynamic content that is to be displayed by the JSP is passed to the JSP from the controller as a JavaBean. In this unit you look at the syntax needed to access JavaBeans from your JSPs. With this support provided for JavaBeans by the JSP tags, you can minimize the JSP syntax needed in your .jsp files to a minimum. Tools such as Rational Application Developer can assist in building the JSP tags needed for access to JavaBeans.
What you should be able to do
After completing this unit, you should be able to:
• Describe the use of the <jsp:usebean> tag in the model-view-controller (MVC) programming model
• Identify the roles of JavaServer Pages, Servlets and JavaBeans in the MVC model
• Describe the functions that JavaBeans perform
• Describe how JavaBeans can manage access to or generation of content
• Describe how a JSP page calls a JavaBean
How you will check your progress
Accountability:
• Checkpoint • Lab exercise
References
http://jcp.org/aboutJava/communityprocess/final/jsr245/index.html JSR-000245 JavaServer Pages 2.1 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-1
Instructor Guide
Figure 20-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
� Describe the use of the <jsp:useBean> tag in the model-view-controller (MVC) programming model
� Identify the roles of JavaServer Pages (JSP pages), Servlets APIs (servlets) and JavaBeans components (beans) in the MVC model
� Explain the functions that beans perform� Describe how beans can manage access to, or generation
of, content� Discuss how a JSP page calls a bean� Explain Rational Application Developer Page Designer
support for the <jsp:UseBean> tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — You are discussing how JSP pages can make use of JavaBeans.
Details — The MVC design is a very good design to use when building Web applications. Since the JSP page is the view component, you need to make sure that your JSP pages are not bogged down with a lot of Java syntax and control and flow. One key to making your JSP pages views is to enclose the dynamic content within JavaBeans. JSP pages have tags to easily access dynamic content from JavaBeans. JSP pages and JavaBeans go hand in hand and are key to using the MVC design in Web applications.
Additional information —
Transition statement — See how this fits in the J2EE architecture.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-3
Instructor Guide
Figure 20-2. Factoring Reusable Components and JSP Pages RD8107.5
Notes:
Your goal should always be to have the JSP page focus on presentation.
3
Factoring reusable components and JSP pages� A JSP source file can become cluttered with Java code
�Scriptlets�Expressions
� JSP pages should only be used to perform presentation� What are the tools and techniques to support this model?
�Dynamic content should be encapsulated in Value beans�Special formatting operations should be encapsulated in
Formatter beans or Custom actions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — You might want to emphasize building your JSP pages entirely from the “Design view” in Page Designer. Also minimize the use of the Script editor in the same tool.
Additional information —
Transition statement — Next: JSP Pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-5
Instructor Guide
Figure 20-3. JSP Pages RD8107.5
Notes:
This picture is often referred to as JSP Model 2 (in Sun Microsystems's early JSP Specification documents).
The typical scenario is likely to be:
1. Request is made to a servlet.
2. The servlet, acting as a Controller, locates or creates one or more objects which will be responsible for generating and encapsulating the desired dynamic content. The objects are JavaBeans or Enterprise JavaBeans (EJBs).
3. The servlet directs the operation of these beans.
4. The servlet then selects the result view, by forwarding control to a selected JSP page. The JSP page is supplied a handle to one or more JavaBeans from which it will extract the dynamic content. The JavaBean is generally provided to the JSP page via either the HttpSession object or the HttpServletRequest object.
4
�View–HTML tags–JSP tags
�Model–InventoryManager–InventoryItem–ShipmentReceived
�Controller–Servlet
Servlet
Database
JSP Page
Browser
Beans -JavaBeans
Results JavaBean
JSP pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Display Pages
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-7
Instructor Guide
Figure 20-4. Display Pages RD8107.5
Notes:
The key here is the attempt to provide the scripting logic encapsulated in pure Java objects (JavaBeans and Servlets).
These assets are developed and maintained by the Application Developer.
Do you need an easy way to access the dynamic content within JSP without writing much code? What you really want is for the JSP page to be a Page Template with simple placeholders for dynamic content (and corresponding syntax to act as these placeholders).
JSP can also be used as a different syntax for building Java-based server side logic. Such uses of JSP are not the focus of this topic.
5
Display pages� Dynamic content accessed and encapsulated in Java objects
(Java classes and JavaBeans )� This Java code is managed separately from page layout
(model and controller)� JSP (as a page template technology) provides a clean and
generally terse syntax for inserting resulting dynamic content into the generated Web page� Typical .jsp is mostly (static) HTML� Dynamic content is pulled from Java classes and beans
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Pages and Results JavaBeans
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-9
Instructor Guide
Figure 20-5. JSP Pages and Results JavaBeans RD8107.5
Notes:
The <jsp:useBean> tag generates Java code which binds a local variable to a JavaBean. This bean may be retrieved from an existing context (page, request, session, or application) or may be instantiated on demand.
6
JSP pages and results JavaBeans� Servlets and the back-end supply dynamic content in a Results
bean� JSP page accesses objects via the <jsp:useBean> tag,
which specifies how to find or create a bean� A bean can be:
�Instantiated from a serialized file or class file �Retrieved (if it already exists) from one of four different
scopes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The <jsp:useBean /> Action
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-11
Instructor Guide
Figure 20-6. The <jsp:useBean /> Action RD8107.5
Notes:
• If the useBean has a body, it is executed only if the result of the useBean execution is the creation of a new bean instance. The body, if it exists, usually contains jsp:setProperty tags. You may also use scriptlets later in the JSP to set properties.
• The default scope is page, if none is specified.
• ID is:
- The local variable name for this bean to use in this JSP
- The bean's name in the scope's namespace
• Type refers to the type of the local variable used to reference the bean.
• Class refers to the actual type of the bean. If omitted, the bean must be found in the named scope.
• BeanName is passed on to the Beans.instantiate method as a filename to locate a serialized bean.
7
�Creates or retrieves a bean instance
�May or may not have a body
<jsp:useBean ... />
or
<jsp:useBean ...>
body
</jsp:useBean>
�<jsp:useBean useBean_attr_list />
–where useBean_attr_list :=�id="beanInstanceName"�scope="page | request | session | application"�typespec:class="classname" class="classname" type="typename" type="typename" beanName="serializedBeanFilename" type="typename"
The <jsp:useBean /> action
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
• All parameter values must be literals; you cannot use variables.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — Point out that the jsp:useBean tag is in XML format.
Transition statement — Next: Retrieving an Existing Bean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-7. Retrieving an Existing Bean RD8107.5
Notes:
In these two examples you are retrieving an existing bean. The first one is from the HttpServletRequest object, and the second one from the HttpSession object. Another possibility (not shown in an example) is to retrieve the object from the ServletContext (application scope).
If the bean does not exist in the scope (that is, there is no object named ”customer” in either the implied or specified scope), an InstantiationException will be thrown. This will alert the developer that there is probably a problem, since it is assumed that the bean already exists in scope. In contrast, if the ”class” attribute is specified instead of ”type,” the object will be created (since it has a public no-argument constructor) and no error will be thrown, thus failing to alert the developer that a potential problem exists. Therefore, when the bean is supposed to exist, you should use the ”type” attribute instead of the ”class” attribute.
8
�id="customer" scope="request" type="com.ibm.domain.Customer": retrieves object named "customer" from the request object. Assigns bean to a local variable named "customer". Types the customer variable as "com.ibm.domain.Customer"
�id="customer" scope="session" type="com.ibm.domain.Customer": same as previously, except that the Customer is retrieved from the session object (HttpSession)
SCOPE Where to look for the JavaBean page PageContext
request ServletRequest
session HttpSession
application ServletContext
Retrieving an existing bean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-15
Instructor Guide
Instructor notes:
Purpose —
Details — Page scope means that the bean scope is within the JSP page only. If you work with custom taglibs, you may use this scope.
Additional information —
Transition statement — Next: Bean Retrieval Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-8. Bean Retrieval Example RD8107.5
Notes:
If the Customer bean has a name property, another approach in the JSP page could be:
<jsp:getProperty name=”customer” property=”name” />
This statement would return the name as a String.
9
Source Servlet
Target JSP page
Request
"customer"Customer
Bean retrieval example...
Customer cust = new Customer();
String n = req.getParameter("cust_name");
cust.setName(n);
...
req.setAttribute("customer",cust);
reqDispatcher("CustOrder.jsp").forward(req,resp);
...
<jsp:useBean id="customer" scope="request"
type="com.ibm.domain.Customer" />
...
<%= customer.getName() %>
...
1
2
1 2
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Creating a Bean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-9. Creating a Bean RD8107.5
Notes:
If you want to create a new bean and the object does not exist in scope, you should use the ”class” attribute of the tag. If the bean does exist, the behavior is similar to specifying the”type” attribute.
If your application expects the bean to exist, it would be better to use the”type” attribute, since an InstantiationException would be thrown to alert you to the abnormal condition of the bean not being present in scope.
In addition to the class having a public, no-argument constructor, it must also be non-abstract.
10
Creating a beanid="customer" scope="request"
class="com.ibm.domain.Customer"
� If object named "customer" does not exist in scope:� Execute public, no-argument constructor for the specified
class� Associate with "customer" scripting variable
� If object named "customer" exists in scope:� Retrieve object from request scope� Assign to scripting variable "customer"� Cast the object to the specified class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Instantiation from a Serialized Bean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-10. Instantiation from a Serialized Bean RD8107.5
Notes:
The JSP container creates an instance of the Customer from a file named serializedCustomer.ser.
11
Instantiation from a serialized beanid="customer" beanName="serializedCustomer" type="com.ibm.domain.Customer"
� Passes "serializedCustomer" to the Beans.instantiate() method.
� Sets the instantiated bean as type "com.ibm.domain.Customer"
� Assigns the bean to a local variable named "customer"
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-21
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: The <jsp:getProperty /> Action
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-11. The <jsp:getProperty /> Action RD8107.5
Notes:
This example shows getting a simple property that can be converted to a String (by calling the Object.toString() method).
12
The <jsp:getProperty /> action� Retrieves the properties in a bean instance and places them in
the implicit out object� Bean instance must have already been defined� Syntax:
<jsp:getProperty name="beanInstanceName"
property="propertyName" />
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-23
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Example: Using a JavaBean
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-12. Example: Using a JavaBean RD8107.5
Notes:
In this example you are looking for a Customer that is in the HttpSession object (session scope). Since class is specified, a create is executed if the Customer instance is NOT found in the specified scope (session). If the bean is created, it must be placed in the specified scope (session in this case).
The code needed to find the object in the specified scope and to create it if the object isn't found is generated by the JSP container when the JSP is compiled.
13
<html>
<head>
<title>Simple JavaBean</title>
</head>
<body>
<jsp:useBean class="com.ibm.domain.Customer“
id="customer" scope="session" />
<H1>Here are the test areas available for
<jsp:getProperty name="customer“
property="firstName" />
</H1>
...
</body>
</html>
Example: using a JavaBean component
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: The <jsp:setProperty /> Action
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-13. The <jsp:setProperty /> Action RD8107.5
Notes:
In the first of the four cases, the property whose name is propertyName is set to the value obtained by evaluating propertyValue (which might be an expression) at runtime.
In the second case, the property whose name is propertyName is set to the value of the request parameter named paramName.
In the third case, the property whose name is propertyName is set to the value of the request parameter with the same name.
In the fourth case, the setProperty tag iterates over the current ServletRequest parameters, matching parameter names to property names, and setting each property to the value of the matching parameter.
14
The <jsp:setProperty /> action� Sets the value of properties in a bean instance.� Two variants:
�Set properties from runtime expression�Set properties from parameters in request object
� Syntax:
<jsp:setProperty name="beanInstanceName" setProperty_prop_expr />
�where setProperty_prop_expr is one of the following:� property="propertyName" value="propertyValue"
� property="propertyName" param="paramName"
� property="propertyName"
� property="*"
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: JavaBeans in a JSP - Example (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-14. JavaBeans in a JSP - Example (1 of 2) RD8107.5
Notes:
Here JSP actions are used to refer to a bean which is accessed from the session scope.
The session scope is used because you are maintaining a session with the client, and the client is already logged on.
15
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD>
<META name="GENERATOR" content="IBM WebSphere Page Designer V3.5.2 for Windows">
<META http-equiv="Content-Style-Type" content="text/css">
<META http-equiv="Content-Style-Type" content="text/css">
<TITLE></TITLE>
</HEAD>
<BODY>
<TABLE width="800" height="270" cellpadding="0" cellspacing="0">
<TBODY>
<TR class="tstnav">
<TD width="645" style="...">
<jsp:useBean type="com.ibm.domain.Customer" id="customer" scope="session" />
<FONT color="#00ff00" size="5" face="Comic Sans MS">Welcome back,
<jsp:getProperty name="customer" property="firstName" />
<jsp:getProperty name="customer" property="lastName" />
</FONT><BR>
JavaBeans components in a JSP page: example (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: JavaBeans in a JSP - Example (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-15. JavaBeans in a JSP - Example (2 of 2) RD8107.5
Notes:
This part of the JSP page contains only static content. However, ExamCommand maps to a servlet which forwards control to other JSP pages which will also use the customer bean to get information to be displayed.
16
<BR>
<BR>
<A href="/ILSCS01/ExamCommand?command=displayTestAreas">List of Available Tests</A><BR>
<BR>
<A href="/ILSCS01/ExamCommand?command=displayTestRecords">Your Test Records</A><BR>
<BR>
<A href="/ILSCS01/ExamCommand?command=updateProfile">Update your profile</A>
</TD>
</TR>
</TBODY>
</TABLE>
</BODY>
JavaBeans components in a JSP page: example (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: JSP Results
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-16. JSP Results RD8107.5
Notes:
17
JSP results
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Bean Creation Roadmap
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-17. Bean Creation Roadmap RD8107.5
Notes:
This shows how the JSP page tries to find an object, and when it creates the object if one is not found in the specified scope.
If “type=” is coded in the <jsp:useBean> tag, the assumption is that the bean already exists. If the bean cannot be located, it is an error.
18
throw exception
bean retrieved
is Bean found in scope? noyes
yesno
yesno is class
provided?
is beanName provided?
load from file -bean retrieved(Possible exceptions)
create (throw exception on create error)
Bean creation roadmap
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-35
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-18. Page Designer and JSP Pages RD8107.5
Notes:
You can access the Insert JavaBean dialog from by either positioning the cursor and selecting JSP Insert Bean... from the Rational Application Developer menu, or by dragging and dropping a Bean from the Palette view. You can also add beans without the dialog simply by dragging and dropping them from the Project Explorer or other navigators.
19
Page designer and JSP pages� JSP pages access dynamic data via JavaBean properties in
the MVC architecture� Page Designer provides a visual way to create <jsp:useBean> tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-37
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: jsp:useBean and jsp:setProperty
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-19. jsp:useBean and jsp:setProperty RD8107.5
Notes:
20
jsp:useBean and jsp:setProperty� The JSP page must
contain a JavaBean before you can display properties
� Select Properties from the pop-up menu to see the property sheet
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-39
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-20. Checkpoint RD8107.5
Notes:
Write down your answers here:
21
Checkpoint1. What advantages do JavaBeans components and JSP
pages provide when used together?2. What options are available for the <jsp:useBean> tag?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-41
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
22
Checkpoint solutions 1. In the MVC-based servlet and JSP design, the code written
by the JSP developer can be mostly HTML. When the dynamic content is needed, the developer can use the <jsp:useBean> and <jsp:getProperty> tags to retrieve the data. The JSP developer does not need to know much Java to use the bean, just enough to specify the <jsp:useBean>tag, and retrieve data via the <jsp:getProperty> tags. If a collection is retrieved as part of this data, the JSP developer will need to know (or be provided) some amount of Java loop coding.
2. The tag can specify from which object to retrieve an already existing bean. If the bean is to be constructed from a serialized file, that file is identified. You can also type the bean as a superclass type.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 20-21. Unit summary RD8107.5
Notes:
23
Unit summary� Having completed this unit, you are able to:
�Describe the use of the <jsp:useBean> tag in the model-view-controller (MVC) programming model
�Identify the roles of JSP pages, servlets, and beans in the MVC model
�Explain the functions that beans perform�Describe how beans can manage access to, or generation
of, content�Discuss how a JSP page calls a bean�Explain Rational Application Developer Page Designer
support for the <jsp:UseBean> tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 20. JavaServer Pages with JavaBeans 20-43
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
20-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 21. JSP Expression LanguageEstimated time
00:45
What this unit is about
This unit describes JSP Expression Language (EL) and its use.
What you should be able to do
After completing this unit, you should be able to:
• Understand and create JSP expressions using JSP expression language
• Understand the use of implicit objects in JSP expression language
• Disable expression evaluation when required
• Create and deploy JSP expression functions
How you will check your progress
Accountability:
• Checkpoint
References
http://jcp.org/aboutJava/communityprocess/final/jsr245/index.html JSR-000245 JavaServer Pages 2.1 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-1
Instructor Guide
Figure 21-1. Unit objectives RD8107.5
Notes:
RD7927.0
2
Unit objectives� Having completed this unit, you will be able to:
� Describe and create JSP expressions using JSP expression language (EL)
� Explain the use of implicit objects in JSP EL� Disable expression evaluation when required� Create and deploy JSP expression functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Review the objectives for this unit.
Details —
Additional information —
Transition statement — Next: JSP Expressions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-3
Instructor Guide
Figure 21-2. JSP Expressions RD8107.5
Notes:
3
JSP expressions� Expressions allow JSP pages to dynamically access and
process server-based data� For example, <%= new java.util.Date() %> inserts
the current date (on the server) into the HTTP output stream
� JSP pages and JSP documents have equivalent forms with different syntaxes:� Page: <%= expr %>� Document: <jsp:expression> expr
</jsp:expression>
� Expressions are often used to provide dynamic content to static HTML tags
<INPUT type="text" name="name" value="<%= session.getAttribute("user") %>">
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Provide a brief discussion of JSP expressions to motivate the introduction of JSP expression language.
Details —
Additional information —
Transition statement — Next: Drawbacks of JSP Expressions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-5
Instructor Guide
Figure 21-3. Drawbacks of JSP Expressions RD8107.5
Notes:
4
Drawbacks of JSP expressions� Expressions are Java
�Along with other forms of scripting, they tend to violate separation of responsibilities
� Expressions for simple concepts can become complex�Example: there is a User object in the session scope. To
access the name of that user might require the following:
((User)session.getAttribute(“user”)).getName()
� In JSP Documents, expressions cannot appear inside quotes�Legal:
<INPUT type=“text” name=“name” value=“<%=...%>”>
�Illegal:<INPUT type=“text” name=“name”value=“<jsp:expression>...</jsp:expression>”>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Discuss some of the disadvantages of JSP expressions.
Details —
Additional information —
Transition statement — Next: What is JSP Expression Language?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-7
Instructor Guide
Figure 21-4. What is JSP Expression Language? RD8107.5
Notes:
The addition of Expression Language to the JSP technology facilitates the writing of script-less JSP pages. These pages can use EL expressions but do not use Java scriptlets, Java expressions, or Java declaration elements, so are easier for non-programmers to work with.
Expression Language is inspired by both ECMAScript (JavaScript) and the XPath expression languages. The expert groups of JSR-052 and JSR-152 were reluctant to design yet another expression language and tried to use each of these languages, but found that both fell short in different areas.
An earlier version of EL was used in JSTL 1.0.
If you have pre-EL JSP pages which used the sequence “${“, you can disable expression language evaluation by specifying isELIgnored=”true” in the JSP page directive, or by including an <el-ignored> tag in the deployment descriptor, as shown:
<jsp-config>
<jsp-property-group>
5
What is JSP expression language?� JSP expression language (EL) is a simple language based on:
� Local variables of the current page� Nested properties and accessors to collections� Relational, logical, and arithmetic operators� A set of implicit objects� Extensible functions mapping into static methods in Java
classes� EL is invoked via the construct ${...}� EL may be used:
� In attribute values for standard and custom actions� Within template text
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
<el-ignored>true</el-ignored></jsp-property-group>
</jsp-config>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-9
Instructor Guide
Instructor notes:
Purpose — Provide a brief introduction to Expression Language.
Details —
Additional information —
Transition statement — Next: EL Examples
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-5. EL Examples RD8107.5
Notes:
6
EL examples� EL expressions can be used in any attribute that can accept a
run-time expression
<c:if test=“${a<3}”>
...
</c:if>
� EL can be used directly in template text
<h2>
Hello, ${user.firstName} ${user.lastName}
</h2>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-11
Instructor Guide
Instructor notes:
Purpose — Discuss two simple examples of the use of EL.
Details —
Additional information —
Transition statement — Next: Implicit Objects
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-6. Implicit Objects RD8107.5
Notes:
Except for pageContext, these objects are all maps based on similar objects defined in the JSP specification. For example, the sessionScope object is a map that maps all session-scoped attribute names to their values. It can be regarded as being equivalent to the session object.
param and header evaluate to Strings, while paramValues and headerValues evaluate to an array of Strings. These may be used to retrieve request parameters (as opposed to objects placed into the request scope as attributes, which are retrieved using requestScope).
If one of these mapped objects is dereferenced with a name that does not appear in the map, the result is null.
Examples:
${pageContext.request.requestURI} - the request's URI (from HttpServletRequest)
${param.productId} - the String value of the productId parameter, or null if not found
7
Implicit objects� Several implicit objects are available to EL expressions used in
JSP pages:�pageContext
�pageScope
�requestScope
�sessionScope
�applicationScope
�param
�paramValues
�header
�headerValues
�cookie
�initParam
Example:
<%= session.getAttribute(“name”) %>
is equivalent to
${sessionScope.name}
Error JSP page examples:
${pageContext.errorData.requestURI}${pageContext.errorData.throwable}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-13
Instructor Guide
${paramValues.productId} - the String[] containing all values of the productId parameter, or null if not found
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — List and discuss EL's implicit objects.
Details —
Additional information —
Transition statement — Next: Syntax Overview
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-15
Instructor Guide
Figure 21-7. Syntax Overview RD8107.5
Notes:
Expression Language follows ECMAScript (the standardized version of JavaScript) in unifying the treatment of the . and [] operators.
expr-a.identifier-b is equivalent to expr-a[“identifier-b”].
The following steps are used to evaluate expr-a[expr-b]:
1. Evaluate expr-a into value-a
- If value-a is null, return null.
2. Evaluate expr-b into value-b
- If value-b is null, return null.
3. Process according to type of value-a
- If value-a is a Map:
• If !value-a.containsKey(value-b) then return null.
• Otherwise, return value-a.get(value-b).
8
Syntax overview� Variables are accessed by name� Generalized [ ] and . operators
�Can be used to access� Maps� Lists� Arrays of objects� JavaBeans properties
�Can be nested arbitrarily� Relational comparisons� Arithmetic and logical operators
Example: to access the name property of the userbean in session scope:
${sessionScope.user.name}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
- If value-a is a List or array:• Coerce value-b to int (if coercion can't be performed raise error).
• If value-a.get(value-b) or Array.get(value-a, value-b) throws ArrayIndexOutOfBoundsException or IndexOutOfBoundsException return null (if other exception thrown, raise error).
• Otherwise, return value-a.get(value-b) or Array.get(value-a, value-b), as appropriate.
- If value-a is a JavaBeans object
• Coerce value-b to String
• If value-b is a readable property of value-a return result of the value-b getter (if this throws an exception, raise error)
- Otherwise raise an error.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-17
Instructor Guide
Instructor notes:
Purpose — Provide a brief discussion of EL syntax.
Details — The student notes provide a detailed explanation of the meaning of the [ ] and . syntax, but instructors should emphasize how intuitive it is.
Additional information — Be sure to compare the example in the slide with the bad example shown on the slide entitled Drawbacks of JSP Expressions.
Transition statement — Next: Basic Syntax Elements
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-8. Basic Syntax Elements RD8107.5
Notes:
Expressions may also contain parentheses.
Strings may be enclosed by quotation marks or apostrophes. Either can be escaped with a backslash if necessary, but it is not necessary to escape apostrophes appearing inside strings enclosed by quotation marks, or vice versa.
The empty operator can evaluate whether an object is empty or null. empty obj returns true if obj is any of the following:
null
A String of length zero
A Map, Collection or array with no elements
Many of the operators have text alternatives: div, mod, and, or, not, ne, le, ge, gt, lt, eq. All of these are considered reserved words, as are empty, null, instanceof, true and false.
9
Basic syntax elements�Literals�Boolean, integer, floating point, string, and null
�Operators�Accessor
. []
�Arithmetic+ - * / %
�Relational== != < > <= >=
�Logical&& || !
�Emptyempty
�Conditional? :
${param.cost * 1.085}
${empty sessionScope ? “yes” : “no”}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-19
Instructor Guide
Instructor notes:
Purpose — Discuss basic building blocks of EL syntax.
Details —
Additional information —
Transition statement — Next: Named Variables
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-9. Named Variables RD8107.5
Notes:
10
Named variables� EL contains a variable resolver that will search the page,
request, session, and application scopes for values� For example:
�A servlet method contains the code:session.setAttribute("user", aUser);
�The servlet then forwards to a JSP page with the following EL expression: ${user}
�The variable resolver resolves the name to the object in:sessionScope.user
� If the attribute is not found in any scope, null is returned� The specification is vague as to what happens when like-
named attributes are found in more than one scope
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-21
Instructor Guide
Instructor notes:
Purpose — Explain how the EL variable resolver works.
Details —
Additional information —
Transition statement — Next: Functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-10. Functions RD8107.5
Notes:
11
Functions � EL functions
�Can be mapped to static Java methods in any Java class�Can be invoked in an EL expression�Provide some of the functionality of custom tags, but much
more simply
<%@ taglib prefix="stock" uri="/stockfnslib" %>...<TR>
<TD>IBM</TD><TD>${stock:lookup("IBM")}</TD>
</TR><function>
<name>lookup</name><function-class>com.ibm.Stockfns</function-class><function-signature>
java.lang.String lookup(java.lang.String)<function-signature>
</function>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-23
Instructor Guide
Instructor notes:
Purpose — Discuss EGL functions.
Details —
Additional information —
Transition statement — Next: Functions Example - Add Two Numbers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-11. Functions Example - Add Two Numbers RD8107.5
Notes:
12
Functions example: add two numberspublic class AddFunction {
public static int addMethod(String x, String y){
int a=0; int b=0;a=Integer.parseInt(x);
b=Interger.parseInt(y);
return a+b; }
} <function> <name>addMethod</name><function-class>AddFunction</function-class><function-signature>int addMethod(java.lang.String,
java.lang.String) </function-signature>
</function>
<%@ taglib uri="/WEB-INF/tld/addfunction.tld" prefix=‘af' %> <HTML>
….The total amount is ${af:addMethod(amt1, amt2)}
</HTML>
Java class
Tag Library Descriptor
JSP
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-25
Instructor Guide
Instructor notes:
Purpose — Provide an example of function definition and usage.
Details —
Additional information —
Transition statement — Next: EL Support
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-12. EL Support RD8107.5
Notes:
13
EL support� The JSP compiler in WebSphere Application Server and
Rational Application Developer supports EL�Required for JSP 2.0 compliance
� Rational Application Developer does NOT provide explicit support�No content assist�No validation�No wizards�No palette items or snippets
Java, not EL
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-27
Instructor Guide
Instructor notes:
Purpose — Discuss the level of support for EL in current versions of WebSphere Application Server and Rational Application Developer.
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-13. Checkpoint RD8107.5
Notes:
Write down your answers here:
14
Checkpoint1. How can you recognize an EL expression?2. In what two places can you use EL?3. Which EL implicit object contains the attributes of the HTTP
session?4. How are the Java functions that underlie EL functions
restricted?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
15
Checkpoint solutions1. EL expressions are enclosed between ${ and }.2. EL may be used in tag attributes and in template text.3. sessionScope
4. They must be public static.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 21-14. Unit summary RD8107.5
Notes:
16
Unit summary� Having completed this unit, you are able to:
� Describe and create JSP expressions using JSP EL� Explain the use of implicit objects in JSP EL� Disable expression evaluation when required� Create and deploy JSP expression functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 21. JSP Expression Language 21-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
21-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 22. JSP Custom TagsEstimated time
00:45
What this unit is about
This unit describes the development and use of JSP custom tags.
What you should be able to do
After completing this unit, you should be able to:
• Describe the advantages of JSP custom tags
• List the major steps in developing and using JSP custom tags
• Describe the basic processing flow for JSP custom tags
• Develop basic tag handler classes to implement JSP custom tags
• Create and modify taglib descriptor files
• Package tag handler classes into taglibs using Application Developer
How you will check your progress
Accountability:
• Checkpoint • Lab Exercises
References
http://www.ibm.com/developerworks/java/library/j-jstl0211.html A JSTL primer, Part 1: The expression language
http://www.ibm.com/developerworks/java/library/j-jstl0318/ A JSTL primer, Part 2: Getting down to the core
http://www.ibm.com/developerworks/java/library/j-jstl0415/ A JSTL primer, Part 3: Presentation is everything
http://www.ibm.com/developerworks/java/library/j-jstl0520/ A JSTL primer, Part 4: Accessing SQL and XML content
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-1
Instructor Guide
Figure 22-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
� Describe the advantages of using JSP custom tags� List the major steps in developing and using JSP custom
tags� Develop basic tag handler classes to implement JSP
custom tags� Create and modify taglib descriptor files� Package JSP taglib implementation classes and taglib
descriptor files� Explain the uses of the JSP Standard Tag Library (JSTL)� Name some of the tags included in the JSTL, and describe
their purposes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — This unit introduces the basic concepts of JSP custom tags. After completion of this unit, the learner should be able to write a simple tag in IBM Rational Application Developer .
Details — After introducing reasons for using JSP tags and basic concepts such as structure of a tag, steps for developing tags, and using the tags in JSP, the unit covers the tag library descriptor (TLD) and classes used to implement tags. The remainder of the unit consists of two examples that show iterative development of a date formatting tag. Each example covers the function of the tag, how it works (processing flow), the TLD used to describe the tag, tag handler code sample and explanation, and how it is used.
Additional information — This unit is a prerequisite for Exercise 9.
Transition statement — Next: JSP Custom Tags Overview
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-3
Instructor Guide
Figure 22-2. JSP Custom Tags Overview RD8107.5
Notes:
You may sometimes see a JSP tag referred to as an action and vice-versa. More precisely, an action is the function performed by a specific tag.
The first group of standard stags mentioned above has to do with bean access from JSP pages. The second group has to do with interaction between JSP pages and other web resources. Both of these groups have already been discussed.
The last group of tags have to do with plugins. The <plugin> tag generates HTML elements that result in download of a Java plug-in to the browser and execution of a specified applet or JavaBean. The <fallback> tag specifies text to include if the browser is unable to support the HTML elements generated by <plugin>. The <params> and <param> tags specify parameters for the plugin.
3
JSP custom tags overview� Nine standard actions must be provided by any compliant JSP
implementation:�useBean, setProperty, getProperty
�include, forward
�plug-in, params, param, fallback
� You (as a developer) can use custom tags to create additional actions beyond the standard set
� Custom actions are invoked via custom tags in a JSP page� Tag libraries are collections of custom tags� Support for JSP custom tags is required by the JSP
specification
<jsp:useBean id="customer" class="com.ibm.model.customer" /><jsp:setProperty name="customer" property="id" value="0" /><jsp:include page=“banner.jsp” />
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Provide overview of use of custom tags in JSP pages.
Details —
Additional information —
Transition statement — Next: Why Use JSP Custom Tags?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-5
Instructor Guide
Figure 22-3. Why Use JSP Custom Tags? RD8107.5
Notes:
Enterprise Web applications are large and complex and required a diverse set of skills to develop. Role-based development is based on the premise that particular parts of the application should be developed by specialists with the most appropriate skills and tools to bring to the particular area. Using JSP custom tags contributes to the role-based development model.
JSPs are primarily to be used for presentation and are the domain of the Web designer and developer, not the Java developer. JSP custom tags provide a way for the Web designer to implement logic to produce complex presentations without the need to become involved in the details of Java.
The use of custom JSP tags for presentation logic is a best practice because it allows the right tools to be used for the right jobs within the Model-View-Controller design pattern.
4
Why use JSP custom tags?� Role-based development
�Model classes (business objects and data storage layers) are developed by Java and EJB developers
�Controller classes (servlets) are developed by Java developers
�View-based JSP pages are developed by HTML developers� Different roles:
�Use different tools�Have different skills
� Best Practice�MVC design is well-established�Use the right tools for the right jobs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Motivate students' interest in tags.
Details —
Additional information —
Transition statement — Next: Steps to Create and Use a Custom Tag Library
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-7
Instructor Guide
Figure 22-4. Steps to Create and Use a Custom Tag Library RD8107.5
Notes:
There are two aspects to custom JSP tags: development and use. Development is concerned with the design and implementation of the tag as a component, whereas use is concerned with combining the functions of the tag with other elements in a JSP page to effect the desired presentation.
5
Steps to create and use a custom tag library� To develop a tag, you need to:
�Design your tags and attributes�Declare the tag in a tag library descriptor (TLD)�Develop a tag handler class�Develop helper classes for the tag (if needed)
� To use a custom tag, the JSP needs to:�Include the tag library using the taglib directive�Code the custom tag with any needed attributes�Test your tags
class 1
class 2
helperclass
TLDJSPpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Explain tag libraries.
Details —
Additional information —
Transition statement — Next: Tag Usage Example
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-9
Instructor Guide
Figure 22-5. Tag Usage Example RD8107.5
Notes:
RD7927.0
This slide demonstrates the use of a JSP custom tag. The taglib directive (line 4) is required. It specifies the URI of a descriptor for a set of tags to be used in the JSP page and a prefix which will refer to the taglib in the current page. It is possible that a page might use several sets of tags; a separate taglib directive would be required for each set.
The JSP custom tag <tl:date> is used near the end of the example. The tag displays the current date in a full format. Notice how the prefix as specified in the taglib prefix attribute (tl) is used to form the complete name of the tag.
6
Tag usage example<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 transitional//EN"><HTML><HEAD><%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix=“tl" %><%@ page language="java"
contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1“
%><TITLE>Date Demo</TITLE></HEAD><BODY><h1>Date Demo</h1><P>Fully formatted date:<tl:date format=”full”/></P></BODY></HTML>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Provide an example of a tag in use.
Details —
Additional information —
Transition statement — Next: JSP Page Without Custom Tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-11
Instructor Guide
Figure 22-6. JSP Page Without Custom Tags RD8107.5
Notes:
If the <tl:date> tag were not available, some Java code dealing with the system date would need to be written as a scriptlet to provide the same function. The tag provides the functionality of the Java code without the baggage of the specific coding implementation and syntax details. The Web developer just wants the tag component to deliver the action of providing a nicely formatted date.
7
JSP page without custom tags
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML><HEAD><%@ page language="java"
contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<TITLE>Date Demo</TITLE></HEAD><BODY><h1>Date Demo</h1><P>Fully formatted date:<% java.util.Locale locale =
pageContext.getRequest().getLocale();java.text.DateFormat fmt =
java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL,locale);
String date = fmt.format(new java.util.Date ()); %><%= date %></P></BODY></HTML>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Show how much worse code without tags is.
Details —
Additional information —
Transition statement — Next: Using Custom Tags with Application Developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-13
Instructor Guide
Figure 22-7. Using Custom Tags with Application Developer RD8107.5
Notes:
The facilities of Page Designer can be used to select the tags that have been defined in the TLD referenced by the JSP's taglib directive. The dialog box shows all the tags that are going to be developed as part of this unit.
The same dialog can also be used to select tags from predefined tag libraries, such as the JSP Standard Tag Library (JSTL). In this case, it automatically generates a <%@taglib> tag.
8
Using custom tags with Rational Application Developer� The Rational Application Developer Page Designer tool has
different ways of selecting a tag for inclusion with JSP 1. Select JSP> Insert Custom2. Drag Custom from the JSP Tags drawer in the Palette
� Select the desired tag from the Insert Custom Tag dialog
12
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Explain how Rational Application Developer supports tag use in JSP files.
Details —
Additional information —
Transition statement — Next: JSP Standard Tag Library (JSTL
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-15
Instructor Guide
Figure 22-8. JSP Standard Tag Library (JSTL) RD8107.5
Notes:
The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement general-purpose functionality common to Web applications, including iteration and conditional processing, data management formatting, manipulation of XML, and database access. Although you learn later in this unit how to create your own tags, be sure to always consider existing tag libraries first, especially the JSTL, which is included with Rational Application Developer as part of its support for JSP 2.0.
The Jakarta Project also makes available a wide selection of tag libraries. Some of these are also included in Rational Application Developer, but the entire set may be downloaded freely from http://jakarta.apache.org/taglibs/.
9
JSP Standard Tag Library (JSTL)� Encapsulates as tags the core functionality of many Web applications� Supports tasks such as:
�Flow (iteration and conditionals)�Manipulation of XML documents�Internationalization tags�SQL tags
� Java EE 1.4 includes both JSP tags and the JSTL�JSTL taglibs are included with Rational Application Developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Explain and motivate use of JSTL.
Details —
Additional information —
Transition statement — Next: Sample JSTL Tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-17
Instructor Guide
Figure 22-9. Sample JSTL Tags RD8107.5
Notes:
10
Sample JSTL tags� Set a variable in a specific scope to a value
�<c:set var="name" scope="scope" value="expression"/>� Display a value, or an alternative if the first value is null
�<c:out value="expr" default="expr" escapeXml="boolean"/> �Example:
Hello <c:out value="${user.name}" default="Guest"/>!
� Conditional execution�<c:choose>, <c:when> and <c:otherwise><c:choose>
<c:when test="${user.role == 'member'}"><p>Welcome, member!</p>
</c:when><c:otherwise>
<p>Welcome, guest!</p></c:otherwise>
</c:choose>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Give examples of some useful but simple JSTL tags.
Details —
Additional information —
Transition statement — Next: ForEach Tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-19
Instructor Guide
Figure 22-10. forEach Tag RD8107.5
Notes:
11
forEach tag� The forEach tag provides flexible iteration through a set of
items� Its targets include:
�Collections, Maps, Iterators, Enumerations�Arrays�Comma-separated values (CSV) data�SQL ResultSets
� Example:<table>
<c:forEach items="${customers}" var=“cust">
<tr>
<td>${cust.name}</td>
<td>${cust.addr}</td>
</tr>
</c:forEach>
</table>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Explore forEachtag.
Details —
Additional information —
Transition statement — Next: Anatomy of a Tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-21
Instructor Guide
Figure 22-11. Anatomy of a Tag RD8107.5
Notes:
Formally, the things we call tags are really XML elements. In XML, the term tag refers to the syntactic units, enclosed in < and > signs, which begin and end such elements. However, as used in the JSP specification, the term tag refers to the entire element.
A tag may have name-value pairs associated with it. These are called attributes. It may also have a body, which is the area between the start and the end tag. A tag that does not have a body needs no end tag, but in that case its start tag should end with /> instead of >.
12
Anatomy of a tag
<tl:asis tab="5">Instructions for logging in to the system:
(1)Enter your Patron identifier in ID field
(2)Enter assigned password in PW field (3)Click on LOGIN button
</tl:asis>
Start tag
Body(optional)
End tag
Attribute (optional)Element
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Tag Examples
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-23
Instructor Guide
Figure 22-12. Tag Examples RD8107.5
Notes:
In the fourth example, list is a list of objects with type domain.Customer, and the iterator goes through them one at a time. In each look, the object which is currently selected is called customer. Thus, this example would result in a list of customer names being displayed on the browser.
13
Tag examples� Basic<tl:fullText />
� With attributes<tl:code language="java“/>
� With attributes and a body<tl:iterator times=10>
<p>"Hello world."</p></tl:iterator>
� Defining scripting variables<tl:iterator name="list" id="customer”
type="domain.Customer"><jsp:getProperty name="customer"
property="name" /></tl:iterator>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Describing Tags to the JSP Container
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-25
Instructor Guide
Figure 22-13. Describing Tags to the JSP Container RD8107.5
Notes:
14
Describing tags to the JSP container� Tags are described with the taglib descriptor (TLD)
�XML file�Describes the tag library�Files use the .tld extension
The TLD:� Defines the syntax of the tags (actions)� Defines the attributes (if any) for the tags
�Specifies if the attribute is optional or required� Specifies the Java class that implements the tag� Specifies if the tag allows or uses a body� Is used by the JSP container to validate the JSP page at
compile time
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: General Format of the TLD (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-27
Instructor Guide
Figure 22-14. General Format of the TLD (1 of 2) RD8107.5
Notes:
The taglib descriptor (TLD) is an XML file and contains a required XML declaration and document type declaration (DTD) that defines the format of the files.
The version of the tab library (<tlib-version>), version of the JSP specification the tag depends on (<jsp-version>), default prefix (<short-name>), and description (<description>) are characteristics that apply to the entire tag library.
Each tag defined in the TLD is delineated by enclosing <tag> elements, which define the tag's name (<name>), its implementing class (<tag-class>), and how the tag body is processed (<body-content>). In this example, the <body-content> tag declares that the tag does not have a body.
15
General format of the TLD (1 of 2)
Defines the date tag
<?xml version="1.0" encoding="UTF-8"?><taglib version="2.1" 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-jsptaglibrary_2_1.xsd">
<tag><name>date</name><tag-class>com.ibm.library.tag.FormattedDate</tag-class><body-content>empty</body-content><description>Display current date</description></tag>
<description>Tag Library from IBM Library System</description><tlib-version>1.0</tlib-version><short-name>ilib</short-name>
Required
Info about TLD
Tag Info
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: General Format of the TLD (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-29
Instructor Guide
Figure 22-15. General Format of the TLD (2 of 2) RD8107.5
Notes:
This slide shows a second tag (date2) that is defined in the TLD. In this case, the <body-content> element states that the body of the tag may contain JSP elements itself. Attributes on the tag are specified by the <attribute> element. The date2 tag has one attribute named format that must be specified.
16
General format of the TLD (2 of 2)
<tag><name>date2</name>
<tag-class>com.ibm.library.tag.FormatDate2</tag-class>
<body-content>JSP</body-content>
</tag></taglib>
<attribute>
<name>format</name><required>true</required>
</attribute>
Action name
Tag handler class implementation
How to process the body
Attribute name (multiple allowed)
Optional (false) or mandatory (true)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Location of TLD File
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-31
Instructor Guide
Figure 22-16. Location of TLD File RD8107.5
Notes:
The actual location of the TLD file could be in a JAR file with the implementing classes or directly in the Web application. Note that the XML Schema location is specified in the TLD and points to the location specified on the slide.
17
Location of TLD file� The TLD file resides in the META-INF directory or
subdirectory when deployed inside a JAR file� It resides in the WEB-INF directory (or some subdirectory of
it) when deployed directly into a Web application
� The XML schema is located at the following URL:http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: JSP Taglib Directive
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-33
Instructor Guide
Figure 22-17. JSP Taglib Directive RD8107.5
Notes:
The taglib directive is required to be placed in a JSP file in order to specify the location of the TLD in the Web Project, as well as the prefix to be used for the tag inside this particular file. The full name of the JSP tag element (in this case tl:date) is a combination of the prefix (in this case, tl) and the value of the <name> element of the tag (in this case, date).
18
JSP taglib directive� The taglib directive tells your JSP page the prefix to be used
for a specific JSP tag library
<!DOCTYPE … ><HTML><HEAD><%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix="tl" %>…<TITLE>date test</TITLE></HEAD><BODY>…<tl:date format="full"/>…</BODY></HTML>
Taglib directive
Taglib usage
Location of TLD
Prefix for this JSP taglib
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Tag Handler Base Classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-35
Instructor Guide
Figure 22-18. Tag Handler Base Classes RD8107.5
Notes:
The tag handler class is defined by the <tag-class> element in the TLD and contains the Java code that implements the tag. Tag handler classes must implement one of the four interfaces other than JspTag shown in the diagram (JspTag is a convenience interface with no methods). Which interface you choose to implement when you write the tag handler class depends on the tasks that tag is required to perform.
For convenience, support classes are also provided. Tag handler classes which extend one of the support classes will automatically implement one of the required interfaces.
SimpleTag and SimpleTagSupport are new in JSP 2.0 and require the developer to override a single method, doTag(). Classic tags may still be developed (and special circumstances may require their use), but they are more complex, require the implementation of more methods, and may involve multi-step processing controlled by a predetermined set of return codes.
19
Tag handler base classes� Tag handlers must implement specific
interfaces or extend specific classes, and must override key methods
� These classes all reside in javax.servlet.jsp.tagext
� JSP 2.0 introduced SimpleTag “classic”
tags
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — Simple tags do not permit scriptlets or expressions in their bodies. Classic tags are still required if the body of the tag may include scripting.
Transition statement — Next: Example Tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-37
Instructor Guide
Figure 22-19. Example Tag RD8107.5
Notes:
In the following pages, you see how to build the tag handler class and tag library descriptor associated with this tag.
20
Example tag� The <transform> tag allows page developers to transform
the contained text in two ways:�Convert it to upper case�Hide it
� The tag has a required mode attribute with the following values:�upper
�hide
� The value of the attribute can be taken from a runtime expression
<m:transform mode="upper"><p>This is text to be transformed.</p></m:transform>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Introduce the tag which is developed over the next few charts.
Details —
Additional information — Be sure to stress the inherent flexibility of such a tag (many more transformations could easily be developed) and its robustness (since letting an expression control the attribute enables dynamic transformation).
Transition statement — Next: Processing Tags with Attributes: How It Works
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-39
Instructor Guide
Figure 22-20. Processing Tags with Attributes: How It Works RD8107.5
Notes:
Conceptually, as parts of a tag are processed by the JSP container, corresponding methods in the tag handler class are executed.
As part of the initialization process, the setMode() method is executed to deliver the value of the mode attribute. If the tag handler is a SimpleTag, all of the processing functions will be coded in the doTag() method. This method has access to the body of the tag, and a way to emit text back to the invoking page.
21
Processing tags with attributes: how it works
<m:transform mode="upper"><p>This is text to be transformed.</p>
</m:transform>
1) Initialize and set attributes (setMode()) 2) Call doTag() method
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: What Needs to Be Done?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-41
Instructor Guide
Figure 22-21. What Needs to Be Done? RD8107.5
Notes:
What needs to be done to use a new tag?
First, a tag handler class needs to be developed. Then a <tag> entry is required in the TLD to specify the name of the tag handler class, and the attribute needs to be defined.
Finally, you can test and use the new tag by including it in a JSP.
22
What needs to be done?� Create the TransformTag class� Update the TLD for the new date tag� Use the new <transform> tag in your JSP pages
handlerclass
TLDJSPpage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — Provide an overview of the steps in tag development.
Details —
Additional information —
Transition statement — Next: The TransformTag Class
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-43
Instructor Guide
Figure 22-22. The TransformTag Class RD8107.5
Notes:
Here is the code for the tag handler class. Note the following:
The class extends SimpleTagSupport.
The attribute mode is present as a member field.
The setter method (setMode()) used to deliver the value of the attribute to the handler. No getter method is required.
23
The TransformTag classpackage com.ibm.library.tag;
import java.io.IOException;import java.io.StringWriter;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.JspFragment;import javax.servlet.jsp.tagext.SimpleTagSupport;
public class TransformTag extends SimpleTagSupport {
String mode = "";
public void setMode(String mode) {this.mode = mode.toUpperCase();
}
// class continues on next page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The doTag() Method
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-45
Instructor Guide
Figure 22-23. The doTag() Method RD8107.5
Notes:
The heart of tag processing a SimpleTag is the doTag() method. In this example, it performs the following tasks:
1. gets the body of the tag with getJspBody()
2. puts the body into a String with invoke()
3. transforms the body according to the mode attribute
4. writes the transformed body back to the JSP page.
5. Good practice would lead us to enclose both the invoke() and write() methods in try-catch blocks, but these have been omitted to make the example more compact.
24
The doTag() method
public void doTag() throws JspException, IOException {
JspFragment body = getJspBody();StringWriter oldbody = new StringWriter();String newbody = null;
body.invoke(oldbody);
if (mode.equals("UPPER")) {newbody = oldbody.toString().toUpperCase();
} else if (mode.equals("HIDE")) {newbody = "";
} else {newbody = oldbody.toString();
}
JspWriter out = getJspContext().getOut();out.write(newbody);
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The Taglib Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-47
Instructor Guide
Figure 22-24. The Taglib Descriptor RD8107.5
Notes:
The main purpose of the taglib descriptor is to map the tag to its handler class, and to specify the attributes that must be delivered.
25
The taglib descriptor
<?xml version="1.0" encoding="UTF-8"?><taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">
<description>Tag Library for Library System</description><tlib-version>1.0</tlib-version><short-name>ilib</short-name>
<tag><name>transform</name><tag-class>com.ibm.library.tag.TransformTag</tag-class><body-content>scriptless</body-content><attribute>
<name>mode</name><required>true</required><rtexprvalue>true</rtexprvalue>
</attribute></tag>
</taglib>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Using the <transform> Tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-49
Instructor Guide
Figure 22-25. Using the <transform> Tag RD8107.5
Notes:
This chart shows the text of a JSP page which will test the tag (META tags have been deleted to save space). Note the JSP taglib directive which defines the location and prefix for the taglib, and note the use of the prefix when using the tag.
26
Using the <transform> tag
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML><HEAD><%@ page language="java"
contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%@ taglib uri="WEB-INF/tld/mytags.tld" prefix="m" %><TITLE>transformDemo.jsp</TITLE></HEAD><BODY><H1>Demonstrate <transform> tag</H1><m:transform mode="UPPER"><P>This is text to be transformed</P></m:transform><P>This text is not to be transformed</P></BODY></HTML>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-51
Instructor Guide
Figure 22-26. Packaging RD8107.5
Notes:
In our examples the tag handler class resides in a package within the Web project that uses it. This is expedient for developing and testing JSP tags, but does not let them be easily shared with other projects. Placing the tag handler classes in a JAR file allows them to be easily used in other projects.
In the screen capture, notice that a URI of http://www.ibm.com/Library/tags has been created to reference the TLD at location /WEB-INF/tld/taglib.tld. The URI can be referenced in the page directive of a JSP using this tag library. The Web Deployment Descriptor stores the map from URI to TLD location. It can be edited in the Tag Lib References area of the Variables tab.
27
Packaging� To facilitate reuse, the tag handler classes can be packaged
together�Place the class files in a JAR�Import the TLD into /WEB-INF/tld�Import the JAR into /WEB-INF/lib
� An additional option is to package the TLD with the class files JAR
� Rational Application Developer provides support for JSP tag library resource references�Web Deployment Descriptor editor
� Add JSP Configuration > Taglib�Allows URI to be specified to reference the TLD
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-53
Instructor Guide
Figure 22-27. Checkpoint RD8107.5
Notes:
Write down your answers here:
28
Checkpoint1. What are some of the advantages of JSP custom tags?2. What are the major steps that must be performed during JSP
custom tag development?3. How are attributes’ values processed in a tag handler class?4. What method of the SimpleTag interface does the main
work of processing a tag?5. What is the purpose of the JSP taglib directive?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
29
Checkpoint solutions1. Advantages of custom tags include:
• Make JSPs easier to develop, test, and maintain• Web developer can focus on presentation (role-based
developmental• Presentation logic is reusable
2. The major steps in JSP custom tag development are:• Design tags and attributes• Write the tag handler class• Construct or modify the TLD• Test in a JSP page
3. Attribute values are processed in a tag handler class through JavaBean-like setter methods.
4. doTag
5. The taglib directive describes the location of the TLD and designates the tag prefix.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-55
Instructor Guide
Figure 22-28. Unit summary RD8107.5
Notes:
30
Unit summary� Having completed this unit, you will be able to:
� Describe the advantages of using JSP custom tags� List the major steps in developing and using JSP custom
tags� Develop basic tag handler classes to implement JSP
custom tags� Create and modify taglib descriptor files� Package JSP taglib implementation classes and taglib
descriptor files� Explain the uses of the JSTL� Name some of the tags included in the JSTL, and describe
their purposes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-56 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 22. JSP Custom Tags 22-57
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
22-58 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 23. JSP Tag FilesEstimated time
00:15
What this unit is about
This unit describes the creatoin and use of JSP Tag Files.
What you should be able to do
After completing this unit, you should be able to:
• Describe the use of JSP tag files
• Call a tag file from a JSP
• Pass body content, parameters and fragments to a tag file
• Create a tag file and use the tag file directives
• Package a tag file
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://java.sun.com/products/jsp JavaServer Pages Technology
http://jcp.org/aboutJava/communityprocess/final/jsr245/index.html JSR-000245 JavaServer Pages 2.1 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-1
Instructor Guide
Figure 23-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Describe the use of JSP tag files�Call a tag file from a JSP page�Pass body content, parameters, and fragments to a tag file�Create a tag file, and use the tag file directives�Package a tag file
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose — This unit introduces the basic concepts of JSP tag files. After completion of this unit, the learner should be able to write a simple tag file in IBM Rational Application Developer.
Details — The module starts out by an overview of a tag file and how to call one. It is then broken into 2 parts:
1. Caller JSP: what you can pass to a tag file
2. Tag File: directives, and objects you can use in a tag file.
01:00
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-3
Instructor Guide
Figure 23-2. Overview of Tag Files RD8107.5
Notes:
3
Overview of tag files� Tag files are another way to build custom actions
�Tag files are JSP pages with .tag or .tagx extensions� They allow non-Java developers to create reusable custom
actions� Are automatically interpreted by the JSP container when
placed in the /WEB-INF/tags folder�Custom action name is the same as the tag file name�Can be further organized in sub-folders of /WEB-INF/tags
� Tag files are separate files that are called from JSP pages Caller JSP page
<info:TagFile1 …/>
<info:TagFile2>…body content…
</info:TagFile2>
TagFile2.tag
TagFile1.tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-5
Instructor Guide
Figure 23-3. Calling a Tag File from a JSP RD8107.5
Notes:
4
Calling a tag file from a JSP page� Resembles the invocation of a custom action
�Tag files are automatically compiled into SimpleTags� More powerful than a <jsp:include>, which can only accept
string parameters in the request� The tag file has access to implicit objects� The tag file can be passed the following:
�Body content: content in between the begin and end tag�Parameters�Fragments: individually named body content
� For example, to call details.tag from a caller JSP page<%@taglib tagdir="/WEB-INF/tags" prefix="info" %>
<info:details loanedCopy="${item}"/>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-7
Instructor Guide
Figure 23-4. Body Content from Caller JSP RD8107.5
Notes:
tagdependent will be interpreted by the tag file.
empty checks to make sure the body content is empty.
scriptless can have EL and actions, just no scripting.
5
Body content from a caller JSP page� Body content can be scriptless, tagdependent, or empty� Tag files can use <jsp:doBody/> to use the body content
�Caller JSP page<info:toUpper>
Uppercase this text
</info:toUpper>
�toUpper.tag (Tag file)<%@ tag body-content="scriptless"%>
<p style="text-transform:uppercase">
<jsp:doBody/>
</p>
Bodycontent
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-9
Instructor Guide
Figure 23-5. Parameters from Caller JSP RD8107.5
Notes:
6
Parameters from a caller JSP page� Passed as attributes to the tag file
�Matches an attribute, with the same name, in the tag file<info:details loanedCopy="${item}"/>
� Can be a dynamic list of attributes�Handled in the tag file by a Map, thus order is not
guaranteed�Can be mixed with defined attributes<info:details
dyna1="first"
loanedCopy="${item}"
dyna2="second"/>
defined parameter mixed in with two
dynamic parameters
parameter
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-11
Instructor Guide
Figure 23-6. Fragments from Caller JSP RD8107.5
Notes:
7
Fragments from a caller JSP page� Enable the calling page to pass in named fragments of body
content� <jsp:body> is used to define the main body content
<info:fragmentTest>
<jsp:attribute name="headerFragment">
<h1>Welcome to the IBM Library System </h1>
</jsp:attribute>
<jsp:attribute name="footerFragment">
System has ${library.size} books
</jsp:attribute>
<jsp:body>
${item.title} ${item.author}
</jsp:body>
</info:fragmentTest>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-13
Instructor Guide
Figure 23-7. Tag Directive in Tag File RD8107.5
Notes:
8
Tag directive in a tag file� Attribute list for the directive
�display-name
�body-content: empty, scriptless, or tagdependent�dynamic-attributes: name of the attribute map�small-icon
�large-icon
�description
�example
�language: scripting language�import: list of imports�pageEncoding
�isELIgnored: true or false� For example
<%@ tag body-content="empty"%>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-15
Instructor Guide
Figure 23-8. Attribute Directive in Tag File RD8107.5
Notes:
9
Attribute directive in a tag file� Maps incoming parameters to variables� Attribute list for the directive
�name
�required: true or false�fragment: true or false�rtexprvalue: true or false�type: type of the attribute�description
� For example<%@ attribute name="loanedCopy" required="true"
type="com.ibm.library.model.LoanedCopy"%>
� Dynamic attribute map is defined in the tag directive<%@tag dynamic-attributes="elements" %>
<c:forEach var="element" items="${elements}" >
${element.key} : ${element.value}
</c:forEach>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-17
Instructor Guide
Figure 23-9. Variable Directive in Tag File RD8107.5
Notes:
10
Variable directive in a tag file� Exposes variables to the calling page� A name can be given to the attribute, or it can be assigned
from an attribute�If it is assigned from an attribute, you need to define an
alias to reference the attribute within the tag file� Attribute list for the directive
�name-given or name-from attribute, with an alias�variable-class
�scope: AT_BEGIN, AT_END, or NESTED�description
� For example �<%@ variable name-given="returnValue" scope="AT_BEGIN" %>
�<c:set var="returnValue" value="5% interest"/>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-19
Instructor Guide
Figure 23-10. Implicit Objects Available in a Tag File RD8107.5
Notes:
11
Implicit objects available in a tag file� Collection of objects available to the tag file
�request: ServletRequest or HttpServletRequest�response: ServletResponse or HttpServletResponse
�jspContext: JspContext for this tag file�session: HttpSession�application: ServletContext�out: JspWriter�config: ServletConfig
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-21
Instructor Guide
Figure 23-11. Example of Calling a Tag File RD8107.5
Notes:
Tag files can contain a tag directive versus a page directive.
A body-content of empty checks to make sure the tag is not wrapping some text.
The type parameter enforces the type of the attribute passed in.
Tag invocation:
The page that calls the tags includes a taglib directive with a tag attribute that indicates the location of the tags.
The attribute defined in the tag files is simply referenced
12
Example of calling a tag file� Tag invocation in ListItems.jsp (Caller JSP)<%@taglib tagdir="/WEB-INF/tags" prefix="info" %>
<info:details loanedCopy="${item}"/>
� Tag definition in details.tag (Tag file)<%@ tag body-content="empty"%>
<%@ attribute name="loanedCopy" required="true"
type="com.ibm.library.model.LoanedCopy"" %>
<h1>Times Renewed = ${loanedCopy.timesRenewed} </h1>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-23
Instructor Guide
Figure 23-12. Tag File with Body Content and a Fragment RD8107.5
Notes:
13
Tag file with body content and a fragment� Tag files can be passed fragments and evaluate them
separately, using <jsp:invoke fragment="fragmentName"/>
�Calling JSP<info:fragmentTest>
<jsp:attribute name="moreContent">
Fragment 1</jsp:attribute>
<jsp:body>Body content
</jsp:body>
</info:fragmentTest>
�fragmentTest.tag<%@ attribute name="moreContent" fragment="true"%>
<jsp:invoke fragment="moreContent" />
<jsp:doBody/>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-25
Instructor Guide
Figure 23-13. Tag File Packaging RD8107.5
Notes:
Tag Files can be organized in sub-folders of /WEB-INF/tags as well.
14
Tag file packaging� A tag file is recognized by the container if placed in the
/WEB-INF/tags/ folder�Tag file does not need TLD
� At tag file placed in the /META-INF/tags folder of a JAR file requires a TLD�The JAR file is placed in the /WEB-INF/lib folder
� Tags can also be packaged as compiled Java classes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-27
Instructor Guide
Figure 23-14. Checkpoint RD8107.5
Notes:
Write down your answers here:
15
Checkpoint1. Where does a tag file need to be placed to be picked up
automatically by the JSP container?2. Why use a tag file instead of writing a custom tag handler?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
16
Checkpoint solutions1. /WEB-INF/tags
2. Allows non-Java developers to create reusable custom actions. Also externalizes any HTML and layout information that may creep into a tag handler class.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-29
Instructor Guide
Figure 23-15. Unit summary RD8107.5
Notes:
17
Unit summary� Having completed this unit, you are able to:
�Describe the advantages of using JSP custom tags�List the major steps in developing and using JSP custom
tags�Develop basic tag handler classes to implement JSP
custom tags�Create and modify taglib descriptor files�Package JSP taglib implementation classes and taglib
descriptor files�Explain the uses of the JSTL�Name some of the tags included in the JSTL, and describe
their purposes�Create and call a tag file from a JSP page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 23. JSP Tag Files 23-31
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
23-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 24. Servlet FilteringEstimated time
00:45
What this unit is about
This unit describes the Servlet Filtering feature of the Servlet API, Version 2.5.
What you should be able to do
After completing this unit, you should be able to:
• Describe the processing flow for filters
• List the Servlet API interfaces and support objects used to implement filters
• Create a new filter using Rational Application Developer
• Create and modify deployment descriptor entries for filters
• Develop a basic filter
• Develop a filter that blocks normal filter chain execution
• Develop a filter that uses a wrapped custom request or response object
How you will check your progress
Accountability:
• Checkpoint • Lab exercises
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-1
Instructor Guide
Figure 24-1. Unit objectives RD8107.5
Notes:
This unit provides an introduction to servlet filters. At the end of the unit you are able to create and deploy servlet filters with Rational Application Developer.
2
Unit objectives� After completing this unit, you will be able to:
� Describe the processing flow for filters� List the Servlet API interfaces and support objects used to
implement filters� Create a new filter using Rational Application Developer� Design deployment descriptor entries for a filter� Develop a basic filter using the appropriate interfaces� Explain a filter that blocks normal filter chain execution� Discuss a filter using a wrapped custom response object
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Introducing Filters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-3
Instructor Guide
Figure 24-2. Introducing Filters RD8107.5
Notes:
Some Web servers like Apache, IIS, and Netscape have implemented proprietary filtering or filtering-like schemes. The servlet filtering API is a J2EE standard (since J2EE 1.3).
3
Introducing filtersFilters:� Are reusable components� Transform (or filter) the content of HTTP requests, responses, and
headers� Can be configured into chains of multiple filters � Are indirectly invoked by client request for a Web resource
�Requested Web resource is at the end of the chain
� Types of filter functionality include:�Process the request for a resource before it is invoked�Process the response for a resource after it is invoked�Modify the response or request object for a Web resource by
wrapping the objects in a custom object�Transfer control to the next filter or Web resource in chain�Block execution of the filter chain
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Typical Uses of Filters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-5
Instructor Guide
Figure 24-3. Typical Uses of Filters RD8107.5
Notes:
Many other uses are possible. Tokenizing filters, for example, might be used with mobile devices to convert the output of an HTML tag to a special byte code the device can interpret, in order to compress the response stream.
The Servlet Filtering API is included in the Java Servlet Specification, and can be viewed on the Web at http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html.
Filters can be thought of pluggable components that can process common services in a standard way without requiring changes to the core processing code of the filtered servlet. The function provided by filters can be added or deleted by changing only the deployment descriptor and not the core processing code of the servlet. Filters can be added or removed without changing the core function of the filtered code, thus allowing a set of services to be configured at run time, rather than during development. Instead of coding conditional logic in a servlet to use a set of ancillary services based on the settings of some flags, one can simply add or remove filters (and their corresponding services) by configuring the deployment descriptor.
4
Typical uses of filters� The Servlet Filtering Specification notes the following as
examples of typical filter uses:�Authentication filters�Logging and auditing filters�Image conversion filters�Data compression filters�Encryption filters�Tokenizing filters�Filters that trigger resource access events�XSLT filters to transform XML content�MIME-type chain filters�Caching filters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Filter Processing Flow
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-7
Instructor Guide
Figure 24-4. Filter Processing Flow RD8107.5
Notes:
Filters are not explicitly seen by the client user. They are invoked when there is a request for a client resource and that client resource has been configured to use filters. Entries in the Web deployment descriptor describe which filters are used for a particular resource; this is covered in more detail later in the unit.
At execution time, the filter typically accesses and possibly modifies the request object (preprocessing), transfers control to the Web resource via the doFilter() method of the FilterChain class, and then accesses (and possibly modify) the response object (post processing) after the doFilter() method completes. Each of these steps is performed within the same method in the filter. As part of the processing, the filter might query, modify, or customize the request and response objects to perform its function. The client request and response are passed to the next filter in the chain as parameters to doFilter().
5
Filter processing flow
Web resource requested by client
Request Response
Access or modify the request
doFilter
Access or modify the response
Filter
Client request for Web resource
Container
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Filter Chain Processing
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-9
Instructor Guide
Figure 24-5. Filter Chain Processing RD8107.5
Notes:
The filter chain is a key concept in servlet filtering.
6
Filter chain processing� Filters can be configured in a chain� A FilterChain object describes the chain� Filters are invoked via nested calls
�Web container invokes doFilter() in first filter in chain� Class: Implementation of javax.servlet.Filter� Parameters:
– Request of type ServletRequest– Response of type ServletResponse– Chain of type FilterChain
�First filter in chain calls doFilter() to invoke the next filter in chain� Referenced from input FilterChain object� Class: javax.servlet.FilterChain� Parameters:
– Request of type ServletRequest– Response of type ServletResponse
�Last entry in the chain is the Web resource
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: doFilter() Nested Calls
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-11
Instructor Guide
Figure 24-6. doFilter() Nested Calls RD8107.5
Notes:
This diagram illustrates how filters are nested. The client request is for the FilterServlet resource. The first filter in the chain (FirstFilter) has the filter's chain passed (by the container) as an input parameter to doFilter(). The filter then uses the doFilter() method of the chain object to call SecondFilter. SecondFilter likewise uses the same mechanism, but it will execute the requested Web resource which is at the end of the chain. Upon return from the end of the chain, control transfers back through the nested calls. The request and response objects are passed as parameters on the chain.doFilter() methods.
7
doFilter() nested calls
doFilter() {
chain.doFilter()
}
doPost() {
……
…….
}
doFilter() {
chain.doFilter()
}
FirstFilter
SecondFilter
FilteredServlet
http://example.com/app/FilteredServlet
Request
Response
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Typical doFilter() Pattern
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-13
Instructor Guide
Figure 24-7. Typical doFilter() Pattern RD8107.5
Notes:
This is a typical processing flow used within the doFilter() method of each of the filters. Note that if a filter chooses to end the chain, it is responsible for creating the response to be sent back to the client. Subsequent filters in the chain, which might have filled in the response object during the normal processing flow, are not available.
8
Typical doFilter() pattern� Examine request object � Possibly wrap request or response object in new custom
object� Invoke next filter in chain with doFilter() method
�Possibly with wrapped objects�May end chain by not performing this step
� Filter must complete response object
� Process response object
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Implementing a Filter
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-15
Instructor Guide
Figure 24-8. Implementing a Filter RD8107.5
Notes:
To implement a filter, the class must be created and entries must be made in the deployment descriptor file (web.xml).
9
Implementing a filter� Create a class that implements the javax.servlet.Filter interface� Implement methods:
�init()�doFilter()�destroy()
� Describe the filter in the deployment descriptor with the filterelement
� Configure the filter’s chaining configuration in the deployment descriptor with the filter-mapping element
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-17
Instructor Guide
Figure 24-9. Application Developer Filter Support RD8107.5
Notes:
Application Developer can create a skeleton of an implementing class for a filter and create entries in web.xml file.
10
Application developer filter support� Creating a filter in the Web perspective
�Right-click the Web project and click New � Filter� Creates a class that implements javax.servlet.Filter� Creates the following methods in the class:
�init�doFilter�destroy
� Creates entries in deployment descriptor to define filter:�filter�filter-mapping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Creating a New Filter in Application Developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-19
Instructor Guide
Figure 24-10. Creating a New Filter in Application Developer RD8107.5
Notes:
The dialogs used in Application Developer to create a filter are shown in the slide.
11
Creating a new filter in Rational Application Developer
Click Next
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Now you will look at some of the Java Servlet API interfaces and support classes that are used to construct servlet filters.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-21
Instructor Guide
Figure 24-11. The javax.servlet.Filter Interface RD8107.5
Notes:
A filter's class must implement the three methods of the javax.servlet.Filter interface. Skeletons for these methods are created by the Application Developer new filter dialogs; you just need to fill in the code.
12
The javax.servlet.Filter interface� Three methods comprise the interface:
�init() throws ServletException� Purpose: To perform filter initialization� Called by container to indicate filter is being placed in service� Parameter:
– config of type FilterConfig
�doFilter() throws ServletException, IOException� Purpose: To perform the filtering� Called by the container each time a request/response pair is passed through the
chain due to a client request for a resource at the end of the chain� Parameters:
– Request of type ServletRequest– Response of type ServletResponse– Chain of type FilterChain
�destroy()� Purpose: To perform filter cleanup.� Called by container to indicate filter is being placed out of service� No parameters
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The javax.servlet.FilterConfig Interface
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-23
Instructor Guide
Figure 24-12. The javax.servlet.FilterConfig Interface RD8107.5
Notes:
Remember that a FilterConfig object is a passed by the container as a parameter of the init() method of the javax.servlet.Fitler class. You can use that object's methods as shown in the slide in the filter's class. Two common uses of the configuration object are to access with the filter's init parameters (which are set in the web.xml file) and get the servlet context.
13
The javax.servlet.FilterConfig interface� There are four getter methods in the interface:
�getFilterName()� Returns the String name of the filter
�getInitParameter()� Returns the the String value of a initialization parameter� Input: name of type String
�getInitParameterNames()� Returns an enumeration of String with the names of the initialization
parameters
�getServletContext()� Returns a reference to the ServletContext in which the filter is
operating
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: The javax.servlet.FilterChainInterface
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-25
Instructor Guide
Figure 24-13. The javax.servlet.FilterChain Interface RD8107.5
Notes:
An object of FilterChain type is supplied by the Web container to the filter's doFilter() method. Use that object as the reference for the doFilter() method when the filter is ready to pass control to the next filter in the chain.
14
The javax.servlet.FilterChain interface� The interface consists of one method:
�doFilter() throws ServletException� Purpose: invoke the next filter in the chain� Called by the container each time a request/response pair is passed
through the chain due to a client request for a resource at the end of the chain
� Inputs:– Request of type ServletRequest– Response of type ServletResponse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next you look at how to describe the filter to the container through the filter and filter-mapping element entries in the deployment descriptor file.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-27
Instructor Guide
Figure 24-14. Describing the Filter RD8107.5
Notes:
If you use the Application Developer's new filter function, entries are added to the web.xml file for the filter you are creating. These entries may need to be modified if you add new filter mappings or change init-parameters, as just a few examples.
15
Describing the filter� Filters are described in the deployment descriptor (web.xml)� Structure of the filter’s describing elements
�<filter>: describes the filter� <filter-name>: name of the filter� <filter-class>: name of the implementing class� <init-param>: describes initialization parameters of the filter
– <param-name>: the initialization parameter name– <param-value>: the initialization parameter value
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Example Of A Filter Description
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-29
Instructor Guide
Figure 24-15. Example of a Filter Description RD8107.5
Notes:
Note that this filter has two init parameters, __FORM_NAME and num.
16
Example of a filter description<filter>
<display-name>FormChecker</display-name>
<filter-name>FormChecker</filter-name>
<filter-class>
com.ibm.filters.FormChecker
</filter-class>
<init-param>
<param-name>__FORM_NAME</param-name>
<param-value>Prime Finder</param-value>
</init-param>
<init-param>
<param-name>num</param-name>
<param-value>Number</param-value>
</init-param>
</filter>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Describing the Filter Mapping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-31
Instructor Guide
Figure 24-16. Describing the Filter Mapping RD8107.5
Notes:
The filter mappings essentially describe the filter chain. When a client request for a Web resource is made, the container consults the deployment descriptor's filter-mapping entries to find a match on either the servlet-name or url-pattern element and determines the corresponding filters for the resource.
Filter mappings can also include a <dispatcher> element which determines when the mapping is active. This is discussed later in this presentation.
17
Describing the filter mapping� Filter mappings are described in the deployment descriptor
(web.xml)� Structure of the filter’s mapping elements
�<filter-mapping>: describes the filter� <filter-name>: name of the filter to be mapped� <servlet-name>: name of the resource to apply this filter
OR� <url-pattern>: URL pattern of the resource to apply this filter
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Examples of Filter Mapping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-33
Instructor Guide
Figure 24-17. Examples of Filter Mapping RD8107.5
Notes:
The first filter, Logger, is mapped with the <servlet-name> element and filters the Prime servlet.
The second filter, WelcomeTrailer, is configured with the <url-pattern> element and filters /Welcome.jsp.
18
Examples of filter mapping<filter-mapping>
<filter-name>Logger</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>WelcomeTrailer</filter-name>
<url-pattern>/Welcome.jsp</url-pattern>
</filter-mapping>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Configuring Filters with Application Developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-35
Instructor Guide
Figure 24-18. Configuring Filters with Application Developer RD8107.5
Notes:
As an alternative to editing the source view of the web.xml deployment descriptor, you can use the Filters tab of the Deployment Descriptor Editor to generate the appropriate XML elements in the web.xml file. Note the portrayal of the filters (and their initialization parameters and mappings) in the Project Explorer.
19
Configuring filters with Rational Application Developer� Configure filters in the Web Deployment Descriptor editor
�Filters details section
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Configuring Filter Chaining
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-37
Instructor Guide
Figure 24-19. Configuring Filter Chaining RD8107.5
Notes:
A Web resource might have multiple filters. This slide describes the rules to determine what order the filters are placed in the chain.
20
Configuring filter chaining� Determined by order of filter-mapping elements in the
deployment descriptor� The last filter in the chain invokes the requested Web resource� Rules:
�First, get filters that match the url-pattern element of the requested Web resource
�Second, get filters that match the servlet-name element of the requested Web resource
� In each case, the filter’s order in the chain is determined by its order in the deployment descriptor file
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Example of Configuring Filter Chaining
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-39
Instructor Guide
Figure 24-20. Example of Configuring Filter Chaining RD8107.5
Notes:
You want to determine the filter chaining order for the Prime servlet. Following the rules from the previous slide:
The url-pattern element for Logger specifies that all URLs match it.
The servlet-name elements for the Prime servlet are FormChecker and PrimeTrailer, per their order of appearance in the deployment descriptor file.
21
Example of configuring filter chaining<filter-mapping>
<filter-name>FormChecker</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Logger</filter-name>
<url-mapping>/*</url-mapping>
</filter-mapping>
<filter-mapping>
<filter-name>PrimeTrailer</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping> Mapping order for Prime servlet:
(1) Logger
(2) FormChecker
(3) PrimeTrailer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Configuring Filters for Reuse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-41
Instructor Guide
Figure 24-21. Configuring Filters for Reuse RD8107.5
Notes:
If possible, you should design a filter to be reused. One way to accomplish this is to use initialization parameters to specify data to be used by the filters. Remember that a filter might be used for a given resource by multiple clients, so the filter classes should be written following general thread safe guidelines, such as avoiding the use of instance variables to maintain state.
22
Configuring filters for reuse� Filters are designed to be reusable components� You can use the same implementation class for different filters
�Different filter-name element�Possibly different init-param element
� Container instantiates an instance of the class for each <filter> elementpublic class AuditFilter implements Filter {
private int mode = 0;
public void init(FilterConfig arg0) throws ServletException {String modeStr = arg0.getInitParameter("mode");if (modeStr.equals("FULL")) {
mode = FULL;} ...
}...
<init-param><param-name>mode</param-name><param-value>FULL</param-value>
</init-param>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Example of Configuring Filter Reuse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-43
Instructor Guide
Figure 24-22. Example of Configuring Filter Reuse RD8107.5
Notes:
Here is one class, com.ibm.filters.Trailer, used by different filters, WelcomeTrailer and DatabaseTrailer. Note that the <init-param> elements are different for each of the filter instances.
23
Example of configuring filter reuse<filter>
<filter-name>WelcomeTrailer</filter-name>
<filter-class>com.ibm.filters.Trailer</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Watch for our new Web Site!
</param-value>
</init-param>
</filter>
<filter>
<filter-name>DatabaseTrailer</filter-name>
<filter-class>com.ibm.filters.Trailer</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Sorry, but the database is currently down.
</param-value>
</init-param>
</filter>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Filters with RequestDispatcher
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-45
Instructor Guide
Figure 24-23. Filters with RequestDispatcher RD8107.5
Notes:
Earlier versions of the servlet specification did not clarify whether filters needed to be invoked when requests were redirected using RequestDispatcher: that is, whether filters can be invoked using forward() or include() requests. Servlet 2.4 provides the ability to configure filters that are invoked with forward() and include() calls. This can be done by using the new <dispatcher> element in the deployment descriptor.
24
Filters with RequestDispatcher� Ability to configure filters that are invoked under RequestDispatcher with forward and include calls
RequestFilters
Forward / IncludeFilters
Web Resource
Filters
Response
Request
Response
Servlet v2.4
Servlet v2.3
Web Resource
Web Resource
Web Resource
Forward / Include
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Dispatcher Element
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-47
Instructor Guide
Figure 24-24. Dispatcher Element RD8107.5
Notes:
These elements may be added manually to the deployment descriptor (web.xml) source, or they may be chosen when adding mappings from the Filter tab of the deployment descriptor editor.
25
Dispatcher element� New <dispatcher> element in the deployment descriptor:
�REQUEST� Filter if request is directly from a client
�FORWARD� Filter if request is from RequestDispatcher.forward method
�INCLUDE� Filter if request is from RequestDispatcher.include method
�ERROR� Filter if request is due to error redirection mechanism
� REQUEST is the default when there is no <dispatcher> element<filter-mapping>
<filter-name>Customer Filter</filter-name> <url-pattern>/customers/*</url-pattern> <dispatcher>FORWARD</dispatcher><dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping><filter-name>Account Filter</filter-name> <servlet-name>CustomerServlet</servlet-name> <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — You will now look at sample code for three filters.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-49
Instructor Guide
Figure 24-25. Filter Code Examples RD8107.5
Notes:
For the remainder of the unit, three example filters will be described.
26
Filter code examples� Example Filters:
�Logger is a simple filter that performs elapsed execution time logging for a servlet.
�FormChecker is a filter to check form syntax. It blocks execution of the chain if form is not correct.
�Trailer is a filter that appends a message to the end of the Web resource’s response page. It uses a custom response object.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — If students carp about the uninformative parameter names used in the examples (arg0, arg1, ...) point out that these are the names generated by the Rational Application Developer Servlet wizard.
Transition statement — Next: Logger Filter: Function Description
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-51
Instructor Guide
Figure 24-26. Logger Filter: Function Description RD8107.5
Notes:
The Logger filter displays the execution duration time of the Web resource that it filters in the Web server's event log.
27
Logger filter: function description� A simple logging filter� Calculates servlet’s execution time in milliseconds� Displays the time in the server’s event log
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Logger Filter: Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-53
Instructor Guide
Figure 24-27. Logger Filter: Deployment Descriptor RD8107.5
Notes:
28
Logger filter: deployment descriptor<filter>
<filter-name>Logger</filter-name>
<display-name>Logger</display-name>
<filter-class>
com.ibm.filters.Logger
</filter-class>
</filter>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Logger Filter: init() and destroy() Methods
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-55
Instructor Guide
Figure 24-28. Logger Filter: init() and destroy() Methods RD8107.5
Notes:
The init() method copies the FilterConfig object provided by the container to an instance variable for later use in doFIlter().
29
Logger filter: init() and destroy() methodspackage com.ibm.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Logger implements Filter {
FilterConfig config;
public void init(FilterConfig arg0)
throws ServletException {
config = arg0;
}
public void destroy() {
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-56 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Logger Filter: doFilter() Method
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-57
Instructor Guide
Figure 24-29. Logger Filter: doFilter() Method RD8107.5
Notes:
Note that this method has the three parts typical of a doFilter() pattern: process request, transfer control to the next filter or Web resource, and process the response.
30
Logger filter: doFilter() methodpublic void doFilter (ServletRequest req,
ServletResponse resp, FilterChain chain)
throws ServletException, IOException {
long before = System.currentTimeMillis();
chain.doFilter(req, resp);
long duration = System.currentTimeMillis() - before;
String msg = “Servlet duration: " +
duration + “milliseconds";
config.getServletContext().log(msg);
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-58 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Logger Filter: How It Works
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-59
Instructor Guide
Figure 24-30. Logger Filter: How It Works RD8107.5
Notes:
If it is important that ONLY the servlet be timed, care should be taken to make sure that Logger is last in the list of filters in web.xml.
31
Logger filter: how it works� Gets timestamp from system� Uses the doFilter() method of the FilterChain object to
invoke the next filter� Upon return from doFilter(), calculates duration� Composes a message with duration� Uses the config object (FilterConfig) to get the servlet
context� Uses the ServletContext.log method to write a message
to the servlet’s event log
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-60 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker Filter: Function Description
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-61
Instructor Guide
Figure 24-31. FormChecker Filter: Function Description RD8107.5
Notes:
This filter illustrates how a filter can block the normal flow of the filter chain by testing for some condition and simply not invoking the chain based on the results. In this case, the filter is responsible for filling in the response, which it does by forwarding to a JSP.
32
FormChecker filter: function description� Checks that specified fields in a form have non-empty values� Filters a servlet that is the Action URL for a FORM tag� Field names are entered as the filter’s init-param names
�Example: <param-name>firstname</param-name>� Field labels are entered as the filter’s init-param values
�Example: <param-value>First Name</param-value>� Parameter name __FORM_NAME is reserved
�Value is the name of the form (for example, Order Entry Form)� If one or more errors is found, the filter forwards the list of missing fields
to a JSP page that lists the form’s name and the form fields that are missing or have empty values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-62 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker Filter: Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-63
Instructor Guide
Figure 24-32. FormChecker Filter: Deployment Descriptor RD8107.5
Notes:
The __FORM_NAME init-param specifies the name of the form, Prime Finder.
The num init-parm corresponds to a required test input field named num on the form.
The filter is mapped to the Prime servlet, which generates prime numbers.
33
FormChecker filter: deployment descriptor<filter>
<filter-name>FormChecker</filter-name>
<display-name>FormChecker</display-name>
<filter-class>com.ibm.filters.FormChecker</filter-class>
<init-param>
<param-name>__FORM_NAME</param-name>
<param-value>Prime Finder</param-value>
</init-param>
<init-param>
<param-name>num</param-name>
<param-value>Number</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FormChecker</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-64 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker Filter: init() and destroy() Methods
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-65
Instructor Guide
Figure 24-33. FormChecker Filter: init() and destroy() Methods RD8107.5
Notes:
As with the previous example, FormChecker implements the init() and destroy() methods in a way typical of many other filters. The config object is used in this filter to access the servlet context within the doFilter() method.
34
FormChecker filter: init() and destroy() methodspackage com.ibm.filters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FormChecker implements Filter {
FilterConfig config;
public void init(FilterConfig arg0)
throws ServletException {
config = arg0;
}
public void destroy() {
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-66 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker: doFilter() Method (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-67
Instructor Guide
Figure 24-34. FormChecker: doFilter() Method (1 of 2) RD8107.5
Notes:
The first part of the method deals with checking to see if any request parameter (as identified by the init-param values of the filter) does not exist or has an empty value. If the field is missing or empty, it is added to an array list object (fieldList), and a flag (doChain) is set to false. The parameter __FORM_NAME is skipped because it holds the form name.
35
FormChecker: doFilter() method (1 of 2)public void doFilter(ServletRequest arg0,
ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
boolean doChain = true;
ArrayList fieldList = new ArrayList();
Enumeration mandatory = config.getInitParameterNames();
if (mandatory != null) {
while (mandatory.hasMoreElements()) {
String parmName = (String) mandatory.nextElement();
if (!parmName.equals("__FORM_NAME")) {
String parmValue = arg0.getParameter(parmName);
String fieldName = "";
if (parmValue == null || parmValue.length() == 0) {
doChain = false;
fieldName = config.getInitParameter(parmName);
fieldList.add(fieldName);
}
}
}
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-68 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker Filter: doFilter() Method (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-69
Instructor Guide
Figure 24-35. FormChecker Filter: doFilter() Method (2 of 2) RD8107.5
Notes:
This part of the code acts upon the decision made in the first part. If all of the mandatory fields are filled in, then doChain is true, so the doFilter() method is invoked and the Prime servlet is executed (along with any other filters further down the chain than FormChecker).
If doChain is false, the array list of field names that were missing or had empty values is added as an attribute to the request, and control is forwarded to a JSP page named BadForm.jsp. This page will display a response that notifies the user as to which fields have missing values.
Note that this filter might also be used in testing to warn developers that they had left a required field off of a page.
36
FormChecker filter: doFilter() method (2 of 2)if (doChain) {
arg2.doFilter(arg0, arg1);
} else {
String formNameValue =
config.getInitParameter("__FORM_NAME");
String formName =
(formNameValue == null) ? "Form" : formNameValue;
arg0.setAttribute("formname", formName);
arg0.setAttribute("fieldlist", fieldList);
config.getServletContext().getRequestDispatcher
("/BadForm.jsp").forward(arg0, arg1);
}
}
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-70 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: FormChecker Filter: How It Works
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-71
Instructor Guide
Figure 24-36. FormChecker Filter: How It Works RD8107.5
Notes:
37
FormChecker filter: how it works� Mandatory field names are read from the filter’s init-param
values as an Enumeration� Each init-param is tested to see if the request parameter of that
name exists and is non-empty�If the parameter does not exist or is empty, then the field name
(value of the init-param) is added to a list and the doChainflag is set to false (blocking the request)
� If all mandatory fields are non-empty, doFilter passes control to the next filter on the chain, and ultimately to the Prime servlet
� Otherwise, the chain is blocked�The array list of missing field names and the form name (value
of __FORM_NAME init-param) are put into request attributes�Control is forwarded to a JSP file to construct
an error page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-72 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — The final example shows how a filter might change the response from a filter. This requires the use of a ResponseWrapperobject, which is introduced on the next slide, before the example.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-73
Instructor Guide
Figure 24-37. Wrapping Request and Response Objects RD8107.5
Notes:
The next example shows one way of using a custom response object in a filter.
38
Wrapping request and response objects� Filters may wrap the request and response objects to create
new custom request and response objects� The wrapped objects might:
�Override existing methods �Create new methods
� Custom request and response objects are typically created by extending :�HttpServletRequestWrapper
�HttpServletResponseWrapper
� Subsequent methods in the filter chain have access to these new custom objects created by wrapping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-74 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Trailer Filter: Function Description
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-75
Instructor Guide
Figure 24-38. Trailer Filter: Function Description RD8107.5
Notes:
The filter appends the message as an HTML paragraph (the trailer) immediately before the </BODY> tag of the response that was created by subsequent filters in the chain (including the target Web resource). This filter assumes that the response is HTML.
In order for the filter to splice the trailer into the response created by subsequent filters and the Web resource, the custom response object passed to them (via doFilter()) must collect their responses into a String. The getWriter() method of the custom response object is overridden so that a StringWriter is returned instead of a PrintWriter; this has the desired effect of buffering the responses into a String when the filtered resources uses the println() method of the returned writer to generate the response stream. Upon return from doFilter(), the filter can now use the toString() method to extract the response generated by the filtered resource as a string, splice in the trailer message, add </BODY> and </HTML> tags to the string, and finally send that string back to the client.
39
Trailer filter: function description� Appends a message to the end of the response object� The message is stored as a filter init-param� A custom response object is created:
�Extends HttpServletResponseWrapper�Buffers response in a StringWriter�Overrides:
� toString : extracts StringWriter buffer as a String� getWriter: returns PrintWriter based on the StringWriter
�Subsequent filters use the custom getWriter method� The custom response object is passed to the chain instead of the original
response object� After return from the chain, the response is unwrapped, the message is
added to it, and both are written to the original response object
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-76 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Trailer Filter: Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-77
Instructor Guide
Figure 24-39. Trailer Filter: Deployment Descriptor RD8107.5
Notes:
Notice that the filter-mapping element uses the url-pattern element to define which Web resource is to be filtered (that is, the end of the chain).
The result of the filter display “Watch for our new Web Site coming soon!” as a paragraph at the end of the page that Welcome.jsp produces.
40
Trailer filter: deployment descriptor<filter>
<filter-name>WelcomeTrailer</filter-name>
<display-name>Welcome Trailer</display-name>
<filter-class>
com.ibm.filters.Trailer
</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Watch for our new Web Site coming soon!
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>WelcomeTrailer</filter-name>
<url-pattern>/Welcome.jsp</url-pattern>
</filter-mapping>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-78 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Trailer Filter: init() Method
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-79
Instructor Guide
Figure 24-40. Trailer Filter: init() Method RD8107.5
Notes:
The init() method copies the config to an instance variable and also gets the init-param message and puts it in the msg class variable.
The destroy() method, which is empty, is not shown here.
41
Trailer filter: init() methodpackage ibm.com.filters;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletResponse;
public class Trailer implements Filter {
private String msg = "";private FilterConfig config;
public void init(FilterConfig arg0)throws ServletException {config = arg0;msg = config.getInitParameter("msg");
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-80 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Trailer Filter: doFilter() Method
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-81
Instructor Guide
Figure 24-41. Trailer Filter: doFilter() Method RD8107.5
Notes:
The new response object (strResp) is created before the call to chain.doFilter() and passed as one of its parameters. Essentially, strResp holds the responses of the downstream filters in a string so that this filter can then extract and modify them to form the final response to the client.
42
Trailer filter: doFilter() methodpublic void doFilter(ServletRequest arg0,
ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
StringResponse strResp = new
StringResponse((HttpServletResponse) arg1);
arg2.doFilter(arg0, strResp);
PrintWriter out = arg1.getWriter();
String responseString = strResp.toString();
int endBodyIndex = responseString.indexOf("</BODY>");
if (endBodyIndex > -1) {
StringBuffer finalResponse = new
StringBuffer(responseString.substring(0,
endBodyIndex - 1));
finalResponse.append("<P>");
finalResponse.append(msg);
finalResponse.append("</P></BODY></HTML>");
String finalResponseString = finalResponse.toString();
out.write(finalResponseString);
} else {
out.write(responseString);
}
out.close();
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-82 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Custom Response: StringResponse
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-83
Instructor Guide
Figure 24-42. Custom Response: StringResponse RD8107.5
Notes:
This slide shows the implementation code for the custom response object, which extends the HttpServletRespnseWrapper class. The toString() and getWriter() methods are overridden from the base class.
43
Custom response: StringResponsepackage ibm.com.sw284.filters;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class StringResponse extends
HttpServletResponseWrapper {
private StringWriter responseWriterBuffer;
public StringResponse(HttpServletResponse resp) {
super(resp);
responseWriterBuffer = new StringWriter();
}
public String toString() {
return responseWriterBuffer.toString();
}
public PrintWriter getWriter() {
return new PrintWriter(responseWriterBuffer);
}
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-84 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Trailer Filter: How It Works
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-85
Instructor Guide
Figure 24-43. Trailer Filter: How It Works RD8107.5
Notes:
Note that the code assumes the end body tag is exactly </BODY>. This code might be improved by handling the lower and mixed case forms of this tag.
44
Trailer filter: how it works� A new instance of a custom response object (StringResponse) is created� The wrapped response is passed to the next filter (Welcome.jsp) via chain.doFilter()
� The toString method of the StringResponse object extracts the response created by Welcome.jsp
� The </BODY> tag is searched for in the extracted response� Assuming that the </BODY> tag is found:
�A substring of the response up to the </BODY> tag is created�The message is added to the substring� New </BODY> and </HTML> tags are added�The new response is sent to the original request’s PrintWriter
� Otherwise, an unmodified response is sent to the PrintWriter
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-86 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Unit Summary
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-87
Instructor Guide
Figure 24-44. Checkpoint RD8107.5
Notes:
Write down your answers here:
45
Checkpoint1. What interface is implemented to build a filter?2. What object defines the sequence of filter execution? 3. How can a filter change the flow of processing to other
filters?4. What is the position of the user-requested Web resource on
the filter chain? 5. How many instances of a filter does the Web container
create?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-88 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
46
Checkpoint solutions1. The javax.servlet.Filter interface is implemented to
build a filter.2. The FilterChain object defines the sequence of filter
execution. The container passes an object of this type to the first filter. The execution is defined by the filter-mapping elements in the deployment descriptor. The order of execution is determined by the order of matching filter-mapping elements in the deployment descriptor.
3. A filter can control the flow of processing by not calling the FilterChain.doFilter() method. In this case, it is responsible for providing the response object.
4. The requested Web resource is last on the filter chain.5. The container produces one instance of a filter for each
filter element defined in the deployment descriptor.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-89
Instructor Guide
Figure 24-45. Unit summary RD8107.5
Notes:
47
Unit summary� Having completed this unit, you are able to:
� Describe the processing flow for filters� List the Servlet API interfaces and support objects used to
implement filters� Create a new filter using Rational Application Developer� Design deployment descriptor entries for a filter� Develop a basic filter using the appropriate interfaces� Explain a filter that blocks normal filter chain execution� Discuss a filter using a wrapped custom response object
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-90 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 24. Servlet Filtering 24-91
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
24-92 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 25. Servlet ListenersEstimated time
00:30
What this unit is about
This unit describes the Servlet Listener feature of the Servlet API, Version 2.5.
What you should be able to do
After completing this unit, you should be able to:
• Define Servlet Listeners and describe how they can be used in a Web application
• List typical uses of Servlet Listeners
• Describe the major steps used to create Servlet Listeners
• Name the six interfaces used to create Servlet Listeners and when to use each interface
• List the methods defined for each of the Servlet Listeners interfaces and their use
• Describe how to define a Servlet Listener to the Web application
• State the rules for determining the order of execution of multiple Listeners in a Web application
• Describe the facilities of Application Developer used for development of Servlet Listeners
How you will check your progress
Accountability:
• Checkpoint
References
http://java.sun.com/javaee/5/docs/api/ Java Platform Enterprise Edition, v5.0 API Specifications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-1
Instructor Guide
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/ JSR-000154 JavaTM Servlet 2.5 Specification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-1. Unit objectives RD8107.5
Notes:
RD7927.0
2
Unit objectives� After completing this unit, you will be able to:
� Define servlet listeners and how they can be used in a Web application
� List typical uses of servlet listeners� Describe the major steps used to create a servlet listener� Name the six interfaces used to create servlet listeners,
and when to use each interface� List the methods defined for each of the servlet listeners
interfaces, and describe their use� Describe how to define a servlet listener to the Web
application� State the rules for determining the order of execution of
multiple listeners in a Web application� Describe the facilities in Rational Application Developer
used for the development of listeners
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-3
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Basic Concepts of Servlet Event Listeners
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-2. Basic Concepts of Servlet Event Listeners RD8107.5
Notes:
Servlet Listeners were introduced in Servlet 2.3 and extended in Servlet 2.4. They are supported by Rational Application Developer.
The Servlet Specification also defines two more listeners that are less often used:
• HttpSessionActivationListener listens for session activation and passivation.
• HttpSessionBindingListener listens for objects being bound to or unbound from the session.
These two listener types are not further discussed in this unit.
3
Basic concepts of servlet event listeners� What is a servlet event listener?
�A class that can listen and react to certain types of events and state changes in a Web application
� It allows you (as a developer) to:�Let listener objects listen for Web module state changes:
� ServletContext lifecycle: Creation and destruction� ServletContext attributes: Addition, replacement, and removal� HttpSession lifecycle: Creation and destruction� HttpSession attributes: Addition, replacement, and removal� ServletRequest lifecycle: Creation and destruction� ServletRequest attributes: Addition, replacement, and removal
�Execute actions in response to the events� Advantages:
�More control over interactions with application, session, andrequest objects
�Centralized monitoring and response to events
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-5
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Examples of Servlet Listener Use
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-3. Examples of Servlet Listener Use RD8107.5
Notes:
4
Examples of servlet listener use� Examples:
�Monitor start and stop of Web modules to perform startup and shutdown tasks
�Add attributes to ServletContext or HttpSessionobjects on creation
�Monitor creation and destruction of sessions�Log important application events
� Sample Scenario:�When an application starts, the listener is notified and
creates a connection to the database. The connection is stored in a servlet context attribute.
�Servlets access the connection as needed from the servlet context.
�When the Web application is shut down, the listener is notified and closes the database connection.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: How to Create a Servlet Listener
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-4. How to Create a Servlet Listener RD8107.5
Notes:
The zero-argument constructor is provided so that the container (which handles the life cycle of the listeners) can create instances as necessary. The zero-argument constructor does not have to be provided explicitly, as the default constructor often suffices.
5
How to create a servlet listener� Create a class the implements at least one of the six listener
interfaces�ServletContextListener
�ServletContextAttributesListener
�HttpSessionListener
�HttpSessionAttributesListener
�ServletRequestListener
�ServletRequestAttributesListener
� Implement methods in the interface�Methods correspond to specific events�Code logic to respond to events
� Create a public zero-argument constructor for the class� Add the listener to the Web deployment descriptor
� A <listener> element defines the listener
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Selecting Servlet Listener Interfaces
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-5. Selecting Servlet Listener Interfaces RD8107.5
Notes:
Each interface provides a method which the Listener developer can override to react to one of the actions. When one of these actions occurs, the container invokes the method.
6
Selecting servlet listener interfaces� Select the listener interfaces to implement according to
the objects and actions that you want to monitor
javax.servlet.
ServletRequestAttributesListenerAdd attributeRemove attributeReplace attribute
ServletRequest
javax.servlet.
ServletRequestListenerCreateDestroy
ServletRequest
javax.servlet.http.
HttpSessionAttributesListenerAdd attributeRemove attributeReplace attribute
HttpSession
javax.servlet.http.
HttpSessionListenerCreate Destroy
HttpSession
javax.servlet.
ServletContextAttributesListenerAdd attributeRemove attributeReplace attribute
ServletContext
javax.servlet.
ServletContextListenerCreateDestroy
ServletContext
InterfaceActionsObject
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Selecting Methods for ServletContext Events
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-6. Selecting Methods for ServletContext Events RD8107.5
Notes:
Since you are implementing interfaces, you will need to provide an implementation for each of the methods in the interface, even if the method has an empty body.
The methods have arguments that provide information about the events, as follows:
ServletContextEvent: Event class for notifications about changes to the servlet context of an application
ServletContext getServletContext()
Returns the ServletContext that changed.
ServletContextAttributeEvent: Event class for notifications about changes to the attributes of a servlet context
java.lang.String getName()
Returns the name of the attribute that changed on the ServletContext.
java.lang.Object getValue()
7
Selecting methods for ServletContext events � To monitor lifecycle events (ServletContextListener
interface) use:�contextInitialized(ServletContextEvent e)
� Called when the Web application is ready to process requests�contextDestroyed(ServletContextEvent e)
� Called when the Web application is about to be shut down
� To monitor attribute events (ServletContextAttributesListener interface) use:�attributeAdded(ServletContextAttributeEvent e)
� Called after an attribute is added to a ServletContext�attributeRemoved(ServletContextAttributeEvent e)
� Called after an attribute is removed from a ServletContext�attributeReplaced(ServletContextAttributeEvent e)
� Called after an attribute is replaced by another in a ServletContext
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-13
Instructor Guide
Returns the value of the attribute that has been added, removed, or replaced.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Selecting Methods for HttpSession Events
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-15
Instructor Guide
Figure 25-7. Selecting Methods for HttpSession Events RD8107.5
Notes:
The methods have arguments that provide information about the events, as follows:
HttpSessionEvent: Event class for notifications about changes to the HTTP sessions within a Web application
HttpSession getSession()
Returns the session that changed.
HttpSessionBindingEvent: Event class for notifications about changes to attributes in an HTTP Session,
java.lang.String getName()
Returns the name of the attribute that changed on the session.
java.lang.Object getValue()
Returns the value of the attribute that has been added, removed, or replaced.
javax.servlet.http.HttpSession getSession()
8
Selecting methods for HttpSession events � To monitor lifecycle events (HttpSessionListener
interface), use:�sessionCreated(HttpSessionEvent e)
� Called when a session is created�sessionDestroyed(HttpSessionEvent e)
� Called when a session is destroyed
� To monitor attribute events (HttpSessionAttributesListener interface), use:�attributeAdded(HttpSessionBindingEvent e)
� Called after an attribute is added to a session�attributeRemoved(HttpSessionBindingEvent e)
� Called after an attribute is removed from a session�attributeReplaced(HttpSessionBindingEvent e)
� Called after an attribute is replaced by another in a session
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Returns the session that changed.Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Selecting Methods for ServletRequest Events
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-8. Selecting Methods for ServletRequest Events RD8107.5
Notes:
Since you are implementing interfaces, you will need to provide an implementation for each of the methods in the interface, even if the method has an empty body.
The methods have arguments that provide information about the events, as follows:
ServletRequestEvent: Event class for notifications about changes to the servlet Request of an application
ServletRequest getServletRequest()
Returns the ServletRequest that changed.
ServletContext getServletContextt()
Returns the current ServletContext.
ServletRequestAttributeEvent: Event class for notifications about changes to the attributes of a request
java.lang.String getName()
9
Selecting methods for ServletRequest events� To monitor lifecycle events (ServletRequestListener
interface) use:�requestInitialized(ServletRequestEvent e)
� Called when the request is about to come into the scope of the Web application
�requestDestroyed(ServletRequestEvent e)� Called when the request is about to go out of the scope of the Web
application
� To monitor attribute events (ServletRequestAttributesListener interface) use:�attributeAdded(ServletRequestAttributeEvent e)
� Called after an attribute is added to a ServletRequest�attributeRemoved(ServletRequestAttributeEvent e)
� Called after an attribute is removed from a ServletRequest�attributeReplaced(ServletRequestAttributeEvent e)
� Called after an attribute is replaced by another in a ServletRequest
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-19
Instructor Guide
Returns the name of the attribute that changed on the ServletContext.
java.lang.Object getValue()
Returns the value of the attribute that has been added, removed, or replaced.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Defining Listeners to the Web Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-21
Instructor Guide
Figure 25-9. Defining Listeners to the Web Application RD8107.5
Notes:
10
Defining listeners to the Web application � Listeners are defined in the Web deployment descriptor
�The <listener> element defines a listener�More than one listener may be defined
� Container executes listeners in the order that they appear in the deployment descriptor file (web.xml)
� The listener-class file is placed in WEB-INF/classesor packaged in a JAR file in WEB-INF/lib
<listener><listener-class>
com.ibm.library.listeners.SessionCounter</listener-class>
</listener><listener>
<listener-class>com.ibm.library.listeners.LoggerListener
</listener-class></listener>
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Sample Servlet Listener Application (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-23
Instructor Guide
Figure 25-10. Sample Servlet Listener Application (1 of 2) RD8107.5
Notes:
This application tracks the number of HTTP sessions established while the application is running and prints out the maximum number of sessions that were encountered when the server shuts down.
There are four getter and setter methods not shown. The number of sessions and the maximum number of sessions are integers and are stored in the servlet context attributes and the four getter and setter methods control access to these values. The counters need to be managed this way because instance variables in servlet listeners behave just as they do in servlets. The getter and setter for the number of sessions are getCurrentSessions() and setCurrentSessions(). The getter and setter for the maximum number of session are getMaxSessions() and setMaxSessions(). The code for these methods is at the bottom of this note.
When the application starts, the contextIntialized() method is called by the container. This method initializes the counters for the number of sessions and maximum sessions to zero by using the setter methods for the counters. These setter methods store the Integer object representation of the counts in servlet context attributes.
11
Sample servlet listener application (1 of 2)public class SessionCounter implements ServletContextListener, HttpSessionListener {
// Called when web app ready to process requests
// Initialize current session and max session counts to 0
public void contextInitialized(ServletContextEvent e) {
ServletContext sc = e.getServletContext();
setCurrentSessions(sc, 0);
setMaxSessions(sc, 0);
}
// Called when web application is about to be shutdown
// Print out max session count at the console
public void contextDestroyed(ServletContextEvent e) {
System.out.println("Max sessions: " + getMaxSessions(e.getServletContext()));
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
When the application shuts down, the contextDestroyed() method is called by the container and prints out a message that includes the maximum number of sessions. It uses the getter method to obtain the maximum number of sessions counter for a servlet context attribute.The code for handling the creating and destruction of the HTTP sessions is shown on the next slide. These methods maintain the counts of the number of sessions and the maximum number of sessions.
Here is the code for the getter and setter methods mentioned above:
private void setCurrentSessions(ServletContext sc, int currentSessions) {
sc.setAttribute("CURRENTSESSIONS", new Integer(currentSessions));
}
private void setMaxSessions(ServletContext sc, int maxSessions) {
sc.setAttribute("MAXSESSIONS", new Integer(maxSessions));
}
private int getMaxSessions(ServletContext sc) {
return ((Integer) sc.getAttribute("MAXSESSIONS")).intValue();
}
private int getCurrentSessions(ServletContext sc) {
return ((Integer) sc.getAttribute("CURRENTSESSIONS")).intValue();
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information — arg0is used as a parameter (rather than some more informative name) because this is what the Rational Application Developer servlet listener wizard generates.
Transition statement — Next: Sample Servlet Listener Application (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-11. Sample Servlet Listener Application (2 of 2) RD8107.5
Notes:
When a session is created, the sessionCreated() method is executed by the container. The method uses the getter methods for the number of sessions and maximum session to store these value in int variables. The number of sessions is incremented and compared to the maximum sessions. The maximum sessions counter is updated if the current number of sessions exceeds the current maximum sessions. The setter methods store the updated counters back into the servlet context.
When a session is deleted, the sessionDestroyed() method is executed by the container. This method gets the counter for the number of sessions (getCurrentSessions()), decrements it, and stores it back in the servlet context with the setCurrentSessions() method.
12
Sample servlet listener application (2 of 2)// Called when a session is created
// Increment session count and compare to max sessions
public void sessionCreated(HttpSessionEvent e) {
ServletContext sc = e.getSession().getServletContext();
int currentSessions = getCurrentSessions(sc)+ 1;
int maxSessions = getMaxSessions(sc);
if (currentSessions > maxSessions) {
setMaxSessions(sc, currentSessions);
}
setCurrentSessions(sc, currentSessions);
}
// Called when a session is destroyed
// Decrement session count
public void sessionDestroyed(HttpSessionEvent e) {
ServletContext sc = e.getSession().getServletContext();
setCurrentSessions(sc, getCurrentSessions(sc) - 1 );
}
}
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Creating New Servlet Listeners with Wizards
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-12. Creating New Servlet Listeners with Wizards(1 of 2) RD8107.5
Notes:
Application Developer has a wizard that will produce a class skeleton for a listener. On the first page of the dialog you enter the display name and optional description
On the second page, enter the destination folder, Java package, and provide the name of the class.
13
Creating new servlet listeners with wizards (1 of 2)� Rational Application Developer has a Life-cycle
Listener (create listener) wizard
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-13. Creating New Servlet Listeners with Wizards(2 of 2) RD8107.5
Notes:
The third page of the dialog allows you to select the interfaces that you use in the listener class. The six standard listener interfaces are included by default. Remove the interfaces that you do not want.
After clicking Finish, the file you created with the wizard will contain a class skeleton with the class definition and all the methods defined for the interfaces that you selected. You can now add the code to the methods to handle the events. The class is also listed in web.xml.
14
Creating new servlet listeners with wizards (2 of 2)� Remove the interfaces that you do not wish to
implement
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-14. Maintaining the Listener Definition RD8107.5
Notes:
15
Maintaining the listener definition� Rational Application Developer lists listeners in the
Listener node of the Web Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-15. Checkpoint RD8107.5
Notes:
Write down your answers here:
16
Checkpoint1. Define a servlet listener.2. What are the lifecycle actions that can be monitored by a
servlet listener for the ServletContext object? 3. What are the attribute actions that can be monitored by a
servlet listener for a ServletContext object?4. What are the lifecycle actions that can be monitored by a
servlet listener for the HttpSession object? 5. What are the attribute actions that can be monitored by a
servlet listener for a HttpSession object?6. Name the six interfaces that can be implemented to
construct a Servlet Listener class.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-35
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
17
Checkpoint solutions1. A class that can listen and react to certain types of events
and state changes in a Web application.2. Creation and destruction of the servlet context.3. Removal, addition, and replacement of a servlet context
attribute.4. Creation and destruction of an HTTP session.5. Removal, addition, and replacement of a session attribute.6. The six interfaces are ServletContextListener,
ServletContextAttributesListener, HttpSessionListener, HttpSessionAttributesListener, ServletRequestListener and ServletRequestAttributeListener.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 25-16. Unit summary RD8107.5
Notes:
18
Unit summary� Having completed this unit, you are able to:
� Define servlet listeners and how they can be used in a Web application
� List typical uses of servlet listeners� Describe the major steps used to create a servlet listener� Name the six interfaces used to create servlet listeners,
and when to use each interface� List the methods defined for each of the servlet listeners
interfaces, and describe their use� Describe how to define a servlet listener to the Web
application� State the rules for determining the order of execution of
multiple listeners in a Web application� Describe the facilities in Rational Application Developer
used for the development of listeners
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 25. Servlet Listeners 25-37
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
25-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 26. Best Practices for Server-Side Application Dev.Estimated time
00:30
What this unit is about
This unit describes some of the practices that can be applied to the design and development of world-class server-side application systems.
What you should be able to do
After completing this unit, you should be able to identify the important issues involved in server-side application development and testing:
• Identify the important issues involved in server-side application development and testing
• Use layering in the design of a new enterprise application
• List some of the benefits and disadvantages of layering
• Describe the roles that Java EE elements usually play in a layered architecture
• Explain layered architecture and what each layer does
• List Servlet and JSP design considerations
• Explain Servlet and JSP patterns and guidelines
How you will check your progress
Accountability:
• Checkpoint • Discussion
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-1
Instructor Guide
Figure 26-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
� Identify the important issues involved in server-side application development and testing
� Use layering in the design of a new enterprise application� List some of the benefits and disadvantages of layering� Describe the roles that Java EE elements usually play in a
layered architecture� Explain layered architecture and what each layer does� List Servlet and JSP design considerations� Explain Servlet and JSP patterns and guidelines
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-3
Instructor Guide
Figure 26-2. The Layering Concept RD8107.5
Notes:
In thinking about the layering concept as an architectural pattern, we can consider the forces:
- We need a way of dividing work among team members so that they can work concurrently and almost independently on the construction of an application
- An architecture that is simple is easier to explain and to visualise. Simplicity makes it easier to explain an application to new team members, and it makes the application easier to extend or maintain
- The layer idea addresses the way that an application is connected to things in its environment
The layering concept is not a new one. The OSI Reference Model was developed by the International Standards Organization in early 1980's. A simple introduction to the OSI Reference Model can be found at http://www.webopedia.com/quick_ref/OSI_Layers.asp -or- http://www2.rad.com/networks/1994/osi/layers.htm
3
The layering concept� High-level or
architectural pattern� Forces
�Dividing work�Simplicity of
connection between layers
�External connections
� “Layer” or “tier”?�The terms are often
used interchangeably
�“Tier” may imply physical separation
A
B
C
D
Higher layer uses services of lower layer
Layer cake
• C is hidden from A• D is hidden from A and B
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Kyle Brown talks about layering as a pattern at http://www.c2.com/cgi/wiki?FourLayerArchitecture"When people discuss layering, there's often some confusion over the terms layer and tier. Often the two are used as synonyms, but most people see tier as implying a physical separation." [Fowler 02] p19.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-5
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-3. Advantages of Layering RD8107.5
Notes:
4
Advantages of layering� With it, you can see where each object fits into the Big Picture
�Each layer can be understood as a coherent whole without reference to other layers
�Managing complexity through encapsulation �Information hiding
� Layers can be replaced with alternative implementations without changing the higher layers
� Layers can be used to introduce standards� Layers can be reused in several applications� Layers can be tested as units independently of the applications
into which they are integrated � Better division of labour
�Specialists in the technology used in (or in the design of) particular layers
�Each layer has its own operational responsibilities � Can avoid cascading changes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-7
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-4. Disadvantages of Layering RD8107.5
Notes:
Layers can be optimized if layer developers are able to maximize efficiency within their own layer.
The ability to avoid cascading changes was listed, on the previous slide, as a benefit of layering. What is going on here? Layering helps you avoid cascading changes when only the implementation of underlying layers is modified. For example, if a database column is renamed, only the data layer of the application needs to be changed. But consider the classic situation in which the addition of a field to the UI forces the addition of a field to the data layer and all layers in between. In such cases, layering gets in the way.
5
Disadvantages of layering� Cascading changes� Extra layers can adversely affect performance
�More levels of indirection�Transforming one representation into another at each layer
boundary� Layers can also be used to perform optimization and caching
�This could improve performance
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-9
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-5. Two-Layer Architecture RD8107.5
Notes:
6
Two-layer architecture� Also known as two-tier
architecture or client-server architecture.
� Typically:�The client provides the user
interface�The server is a database
� Characteristics:�Multiple applications share a
common database�All processing occurs in the
client
App 1
App 2
App 3
Database
Network
Client Server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-6. Problems with Two-layer Architecture RD8107.5
Notes:
Stored procedures do not model the semantics of the enterprise particularly well; they are normally not well supported by development tools; and they are difficult to debug.
7
Problems with two-layer architecture� The database structure can only partially model the semantics
of the enterprise�It is hard to represent complex business rules
� Where do you put shared processing and logic?�Putting it on the client can cause maintenance problems
� Integrity control largely up to application programmers�This can also be controlled at the database level
� Ramifications of changing the database structure on which multiple applications depend directly�Stored procedures offer some relief by abstracting access
to the database� Data may be spread across multiple databases
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-13
Instructor Guide
Instructor notes:
Purpose —
Details — Students may argue that stored procedures are the solution to the problems of database integrity control and database change control. They are partially right. But stored procedures do not model the semantics of the enterprise particularly well; they are normally not well supported by development tools; and they are difficult to debug.
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-7. Three-layer Architecture RD8107.5
Notes:
This is the 50000 ft view of a layered architecture
“Core J2EE Patterns” divides the presentation layer into the Client and Web layers
Marinescu further divides this layer into Presentation and Application
Presentation Layer
HTML, JSP, Swing, Flash, and so forth
Application Layer
Session management (HTTPSession, for example), syntactic validation, UI workflow.
The "glue"
Marinescu divides the business layer in two
Services
Business workflow
8
Three-layer architecture� The presentation layer deals with all
interaction between the user and the rest of the application
� The business layer encapsulates application-specific business rules�It can also model complex structural
relationships and patterns� The data layer deals with communication
with other systems�For example, databases and other
enterprise information systems�Often an object-oriented model in
software, on top of a relational database
Presentation Layer
Business Layer
Data Layer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-15
Instructor Guide
Transaction control.
May support multiple Application layers
Domain
Application-independent
Marinescu calls the data layer the Persistence layer, the J2EE Tutorial calls it the Enterprise Information System (EIS) Tier
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-17
Instructor Guide
Figure 26-8. Layering in J2EE RD8107.5
Notes:
Roles given to J2EE components depend on approach
For example:
JSP or servlet could implement business logic
Session EJB could form part of data layer
Heuristics for good assignment of roles is the subject matter of this course
9
Java EE Server
Layering in Java EE
WebContainer
ClientMachine
DataBusinessPresentation
DBEJBContainer
JSPs
Servlets
SessionEJBs
EntityEJBsApplication
Container
Browser & Applet
Container
EIS
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-19
Instructor Guide
Figure 26-9. Sample Layered Application (1 of 2) RD8107.5
Notes:
10
Sample implementation of patterns (1 of 2)� What follows is a sample implementation of layering and
design patterns� The terms used in this sample application may vary from the
terms used in your organization or other pattern sites�The next slide contains a list of different pattern resources
that may use different terms� The goal of the sample implementation is to show you how
different patterns fit together�You are not expected to remember pattern names, or know
how to implement this solution� The goal of each slide is to provide a high-level view of each
layer�The notes may go into more detail
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Important: The sample application takes a whole course to explain. The intent of this overview is to get the students interested in patterns and how they can fit together. Highlight the 3 layers, how they fit together and that Transfer Objects flow in between the layers.
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-21
Instructor Guide
Figure 26-10. Sample Layered Application (2 of 2) RD8107.5
Notes:
11
Sample implementation of patterns (2 of 2)� References
�The top Java EE best practices� http://www.ibm.com/developerworks/websphere/techjournal/0701_botz
um/0701_botzum.html
�IBM Patterns for e-business� http://www.ibm.com/developerworks/patterns/
�Java BluePrints� http://java.sun.com/blueprints/
�Java EE Tutorials� http://java.sun.com/javaee/reference/tutorials
�Core Java EE Patterns� http://www.corej2eepatterns.com
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-23
Instructor Guide
Figure 26-11. Sample Layered Application RD8107.5
Notes:
This sample application is from another IBM course that is dedicated to best practices.
Model-view-controller ( MVC ) design pattern demonstrates division of work in a vertical fashion. Layering is a generalization of this concept. MVC is used in the sample application, and additional layers are added to enhance division of work for the purpose of greater flexibility in terms of designing and coding future changes. In addition, multiple implementations of the model can be achieved without impacting controller and view layers. Multiple types of views can make use of the model layer as well. An additional, common extension to the MVC architecture is the explicit inclusion of the data mapping layer which we have implemented using EJB and a simplified version using JDBC.
12
Sample layered application
Data Layer
BusinessLayer
PresentationLayer
Model Helpers (Application business logic)
Thin client GUI (html, JSP)
Servlet, Controller, State Engine
Session Façade
Action Processor Interface
Domain (Data transfer
objects)
EJB Mappers
Data server
EJB Adapters JDBC Adapters
JDBC Mappers
Entity Beans
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — Important: We recommend that you do not spend much time on this slide as the following slides go into more detail. Also this is only one way of implementing a layered architecture. Different variations can be used instead.
Additional information —
Transition statement — Business tier layer
Data access layer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-25
Instructor Guide
Figure 26-12. Presentation Layer (Client) RD8107.5
Notes:
13
Presentation layer (client)� Thin-browser (HTML, JavaScript)� No applets� No application-specific installation on
client machine
Data Layer
Business Layer
Presentation Layer
Servlet
Controller
State Machine
Client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-27
Instructor Guide
Figure 26-13. Presentation Layer (Servlet) RD8107.5
Notes:
14
Presentation layer (servlet)� Manages the requests for domain
state and behavior� Thin (minimum responsibilities)� Manages a static reference to the
controller (dispatcher)� Creates an HttpInteractionBean
to contain the HTTP request, response, and context
� Forwards HttpInteractionBeanto the controller
Data Layer
Business Layer
Presentation Layer
Servlet
Controller
State Machine
Client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — The servlet is deliberately thin with the minimum responsibilities. These include managing a static reference to the controller (dispatcher), creating a HttpInteractionBean to contain the http interaction elements (request, response, context) and forwarding that bean to the controller.
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-29
Instructor Guide
Figure 26-14. Presentation Layer (Controller) RD8107.5
Notes:
The Controller‘s responsibility is to execute the command against the correct state. It interacts with the session to determine the state. Concrete implementations of the abstract HttpController are responsible for the extraction of and invocation of the command. This URI to "Action" mapping is a characteristic of the Apache Struts framework.
15
Presentation Layer
Presentation layer (controller)� Created in Command Servlet
initialization� Controller class name provided as an init parameter to the servlet
� Executes commands against the correct state
� Interacts with the session to determine the state
Data Layer
Business Layer
Servlet
Controller
State Machine
Client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-31
Instructor Guide
Figure 26-15. Presentation Layer (State Machine) RD8107.5
Notes:
The state machine approach means that there is one state object for each defined state in the application, for example LoggedInState and UpdateUserInformationState. State objects define all of the valid actions/commands which can be invoked for the sample application. The State subclasses provide implementations which are appropriate for being in that state. For example, you cannot perform many actions if you are in the LoggedOutState. The state classes are responsible for interacting with the session, the HttpInteractionBean, and providing state transitions for the application.
16
Presentation layer (state machine)� State objects for application states:
�LoggedInState, StartState, and so on
� Abstract class SampleState�One method per command
� State subclasses override methods to implement state-specific handling of commands
� Responsibilities�Extract incoming request
parameters�Invoke the model layer logic�Change to next state
Data Layer
Business Layer
Presentation Layer
Servlet
Controller
State Machine
Client
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-33
Instructor Guide
Figure 26-16. Business Layer (Action Processors) RD8107.5
Notes:
Action processors insulate the controller from the model implementation details and provide the interface to the backend server. All the state machine needs to know about from a model perspective are the action processor interfaces, each of which define the application interface of a set of related actions. There may be different implementations of an ActionProcessor interface for different backends which reside in different packages. For example an EJB versus a non EJB backend implementation.
17
Business layer (action processors)� Not dependent on HTTP� Java interfaces for groups of actions� Example: CustomerActionProcessor
� Insulates the controller from the model
� Implementations for EJB and JDBC technology
� ActionProcessorFactory
�Instantiates Action Processor implementation objects
�Checks properties file for EJB to JavaBean component switch
�Caches action processor singletons
Data Layer
Business Layer
Presentation Layer
DTOs Session Facades
Action Processors
Model Helpers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-35
Instructor Guide
Figure 26-17. Business Layer (Data Transfer Objects) RD8107.5
Notes:
History of DTOs: used to be known as Domain Objects. Now a misnomer.
DTOs are currently polluted with some business logic.
18
Business layer (data transfer objects)� Derived from an object model� Extend framework DomainObject� getMapper method� Serializable for transmission between
the EJB server and servlets
Data Layer
Presentation Layer
Business Layer
DTOs Session Facades
Action Processors
Model Helpers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-36 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-37
Instructor Guide
Figure 26-18. Business Layer (Session Facades) RD8107.5
Notes:
EJBs consist of two major types - entity beans and session beans. Session beans are typically coarse grained in that they can provide application business logic, and one call to a session bean method may result in several actions being taken. These actions can reside within a transaction, as the session bean can manage a transaction via the EJB container provided by WebSphere. All transaction management for the EJBs is performed by session beans. The sample application session beans are implemented using the Facade pattern.
In a distributed architecture, the session beans are where the physical split would be made. Session beans have a very similar interface to the ActionProcessors. The only interface difference is that the Session beans methods must throw RemoteException.
In many EJB architectures, business logic is kept in the Session beans. In our architecture, most of the business logic is moved to the Data Transfer Objects and Model Helper
19
Business layer (session facades)� Purpose
�Transaction management�Remoteability
� Session Façade pattern � Called by ActionProcessor
implementations� Similar methods to ActionProcessors
� Very little business logic (this is in Model helpers instead)
Data Layer
Presentation Layer
Business Layer
DTOs Session Facades
Action Processors
Model Helpers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-38 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
objects. The Session object’s primary responsibility is to manage transactions and supply the distributed interface for the model. They may have application business logic in how backend requests are grouped into transactions. The core enterprise business logic is being kept independent of the persistence framework (EJBs, JDBC) and of the application transactions (session beans).Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-39
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-40 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-19. Business Layer (Model Helpers) RD8107.5
Notes:
Model helpers encapsulate the application specific business logic. The model helpers are Java objects, not EJBs. This factoring is done for the purpose of flexibility in design.
In particular, application logic which may be employed within multiple units of work can be reused without incurring the overhead of EJB to EJB calls. Further, since most of this logic is independent of EJB technology, they can be reused in non-EJB based implementations. When called by session beans, they participate in the EJB transaction and security contexts. Model helpers employ domain objects and mappers to do their job.
20
Business layer (model helpers)� Encapsulate the application-specific
business logic� Java objects, not EJBs� Can be reused in non-EJB based
implementations� Can participate in EJB transaction
and security� Use DTOs and mappers
Data Layer
Presentation Layer
Business Layer
DTOs Session Facades
Action Processors
Model Helpers
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-41
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-42 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-20. Data Layer (Mappers) RD8107.5
Notes:
The role of mappers is to move data from domain objects to persistent data sources and vice versa. The sample application allows for different mapping technologies, specifically JDBC and EJB. Mappers are used by the model helpers to move the data to/from the persistent layer.
21
Data layer (mappers)� Move data from DTOs to persistent
store and vice versa� Used by Model Helpers� Pluggable EJB and JDBC versions� Extend abstract EJBMapper or JDBCMapper
� MapperFactory �Instantiates appropriate mapper�Checks properties file for EJB to
JDBC component switch
Data Layer
Business Layer
Mappers
Entity EJBs
Storage
Presentation Layer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-43
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-44 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-21. Data Layer (Entity EJBs) RD8107.5
Notes:
22
Data layer (entity EJBs)� Manage the interface to the relational
database� Container-managed persistence
(CMP) Business Layer
Presentation Layer
Data Layer
Mappers
Entity EJBs
Storage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-45
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-46 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-22. Decoupling the Layers RD8107.5
Notes:
To illustrate the decoupling between the Business Layer and the Data Layer, consider the need to replace an XML file with a relational database. Perhaps the application has become more popular and needs the kind of heavy-duty backup, indexing and integrity controls that a relational database can provide. Ideally you would like to make this change without making massive changes to the Business Layer.
23
Decoupling the layers� Logical separation
�The three layers need not be separate projects, packages, or even classes
� Preserve the ability to substitute different lower layers Business Layer - does not know
about formatting of data for display, interpreting requests from UI, the database schema or the
type of data store
Presentation Layer - does not know what the application is about (!)
Data Layer - does not know how the data is used
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-47
Instructor Guide
Instructor notes:
Purpose —
Details — We suggest that you discuss with the students what it would mean for the Business Layer to be decoupled from an HTTP-based Presentation Layer. Consider:
• Managing HTTP session state
• Interpreting HTTP requests
• Building HTTP responses
• Handling double-keying of buttons
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-48 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-23. Accessing the Data Layer Directly RD8107.5
Notes:
"Sometimes the layers are arranged so that the domain layer completely hides the data source from the presentation. More often, however, the presentation accesses the data store directly. While this is less pure, it tends to work better in practice. The presentation may interpret a command from the user, use the data source to pull the relevant data out of the database, and then let the domain logic manipulate that data before presenting it on the glass." [Fowler 02] p20.
The classic example of bypassing layers for performance reasons is the direct use by Session EJBs of JDBC to return read-only lists of things.
For a justification of judicious breaking of the rules, refer to [Marinescu 02] p130.
You don't have to have all the layers but….be careful. If possible avoid this “quick and dirty” approach except for very simple applications. Complex extensions to the “prototype should be refactored to include a properly layered approach.
24
Accessing the data layer directly� Sometimes it may be desirable to go straight from the Presentation
Layer to the Data Layer�In this case, the Presentation Layer bypasses the Business Layer�Breaking the decoupling rule and removes many of the advantages
of layering�There may be good reasons for doing this
� Performance� Simpler for trivial domain models� Quick prototypes
�Must be done judiciously� How might this work?
�The Presentation Layer interprets a command from user, uses the Data Layer to pull data from database, uses the Business Layer to manipulate data and presents the data on screen
� Never let the Business Layer or the Data Layer be dependent on the Presentation Layer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-49
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-50 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 26-24. Physical Layering RD8107.5
Notes:
Splitting business logic between the client and the server - "The trick then is to isolate this piece of logic in a self-contained module that isn't dependent on any other part of the system." [Fowler 02] p24.
Avoiding separate processes
Here are some thoughts about the decision between using local and remote EJBs. As you will see, much of our thinking is based on [Fowler 02].
Firstly, let us declare our position in regard to EJBs:
• Entity EJBs are best accessed via local interfaces. For reasons not worth repeating here, client layers typically access entity EJBs through session EJBs, rather than directly. The trend is now to define fine-grained interfaces to entity EJBs, which are deployed in the same container as the session EJBs through which they are accessed.
• Session EJBs typically have course-grained interfaces and are therefore better suited to remote interfaces. But the choice of interface type is not as straight-forward as one might think. The best approach is to define local interfaces for session EJBs and define
25
Physical layering� Where should you put business logic?
�On the client for responsiveness or disconnected use �On the server for ease of control, updatability, and
maintainability�Split between the client and the server, if you can separate
the logic to avoid getting the worst of both worlds� Avoid separate processes, which necessitate remote calls
�Pass-by-value semantics�More complexity�Performance degradation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-51
Instructor Guide
remote interfaces for them, or remote facades for them, only when the need arises to access them remotely.
Here is our rationale for defining local interfaces for session EJBs by default:
• Remote interfaces are slower to access. To minimise the number of calls to remote interfaces, one typically defines the interface in terms of data transfer objects. So one ends up with another set of classes to maintain and a interface to the session EJB layer that is awkward to maintain.
• Martin Fowler defines the First Law of Distributed Object Design thus: "Don't distribute your objects." He recommends that we "fight like a cornered rat to eliminate as many of [the remote interfaces] as you can", creating them only where we absolutely need to deploy components in separate processes. He says, "... there may be some genuine reason that you have to split your application server software. You should sell any grandparent you can get your hands on to avoid this."
• Fowler says, "All things being equal it's best to run the Web and application servers in a single process" unless you cannot do so because, for example, you are using web servers and application servers from different vendors. My own experience suggests that most enterprises adopt this approach.
• In his discussion of the Service Layer pattern, Fowler talks more specifically about the distribution of Service Layer objects (session EJBs in the J2EE world). After acknowledging that Service Layer methods are more suited to remote invocation, he says, "However, remote invocation comes at the cost of extra work to make your Service Layer method signatures deal in Data Transfer Objects (401). Don't underestimate the cost of this work, especially if you have a complex Domain Model (116) and rich editing UIs for complex update use cases! It's significant, and it's painful - perhaps second only to the cost and pain of object-relational mapping. ... Our advice is to start with a locally invocable Service Layer whose method signatures deal in domain objects. Add remoteability when you need it (if ever) by putting Remote Facades (388) on your Service Layer or having your Service Layer objects implement remote interfaces. If your application has a Web-based UI or a Web-services-based integration gateway, there's no law that says your business logic has to run in a separate process from your server pages and Web services. In fact, you can save yourself some development effort and runtime response time, without sacrificing scalability, by starting out with a collocated approach." In regard to the Java implementation of a Service Layer, Fowler says, "My preferred way of applying a Service Layer in J2EE is with EJB 2.0 stateless session beans, using local interfaces, and the operation script approach, delegating to POJO domain object classes. ... Also, with the local interfaces introduced in EJB 2.0, a Service Layer can exploit the valuable transaction services while avoiding the thorny object distribution issues."
• The XP principle of doing the simplest thing first applies here. If it is relatively easy to add it later - and, in the case of remoteability of session EJB interfaces, it is - avoid writing now that thing that you *may possibly* need in the future.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-52 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-53
Instructor Guide
Figure 26-25. Servlet Considerations RD8107.5
Notes:
Security: If the application requires different security behavior for different requests, then this will have to be coded in each servlet.
Testability: Easier to test, and coverage is better when using one servlet for each request. When using only one servlet for the entire application, you'll need to use introspection to find the associated action for each request ,thus making testing more difficult.
26
Servlet considerations� There are many issues surrounding whether having one
servlet per request is the best technique:�Administration
� The more servlets there are, the more there are to register and configure
�Security� Global or local security behavior
�Testability� Easier with one servlet per request
�Profiling � Easier to track performance and usage with one servlet per request
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-54 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-55
Instructor Guide
Figure 26-26. JSP Design Considerations RD8107.5
Notes:
The Indirect Model is referring to the MVC design pattern.
There can be multiple JSPs, each designed to support one of the possible outcomes of a client's request. Based on the results of the business logic, the controller decides which JSP to forward to, and the appropriate response is displayed.
JavaServer pages are recommended to be used for presentation only. The JavaBeans provide the dynamic data, which can be used to populate the resulting dynamic Web page.
Scriptless JSP pages should be the goal.
27
JSP design considerations� Use the Indirect Model programming model
�JSP pages are called indirectly, through a controller (servlet)
�The sole purpose is to provide a response to the client�No control behavior within the JSP page
� Minimize the amount of Java code in the JSP page�Just use the JSP page for display purposes�Can be easily generated and viewed by JSP-aware HTML
page editors�Allows separation of the model and the view�Allows separation of development roles�Use custom tags�Put Java code in beans and call them with the <useBean>
tag
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-56 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-57
Instructor Guide
Figure 26-27. Other JSP Guidelines RD8107.5
Notes:
28
Other JSP guidelines� Set the session page directive attribute to false if session
support is not required� Use the type and class attributes of the use:Bean tag
correctly�The type attribute throws InstantiationException if
object not in scope�The class attribute creates and object if it is not in scope
� Consider guarding JSP pages by placing them in the WEB-INFdirectory
� Avoid hard-coding the context path in a URL�Use the contextPath property of HttpServletRequest
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-58 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-59
Instructor Guide
Figure 26-28. Synchronizer Token: Problem RD8107.5
Notes:
29
Synchronizer token: problem� Users can accidentally send
duplicate requests to the server� Example:
� The user completes a form to request an account transfer
� The servlet is invoked, and the new balance is displayed
� The user goes on to perform another action in the Web application (another page)
� The user clicks the Backbutton on the browser
� The browser displays a dialog indicating that the data is unavailable, and asking the user whether the form data should be re-posted
� If the user elects to re-post, the funds will be transferred again
InputTransfer
Information
InputTransfer
Information
CurrentBalance
CurrentBalance
AcctTransferServlet
AcctTransferServlet
Back
AnotherPage
AnotherPage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-60 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-61
Instructor Guide
Figure 26-29. Synchronizer Token: Solution (1 of 2) RD8107.5
Notes:
30
Synchronizer token: solution (1 of 2)� Synchronizer Token pattern
� Use a token to monitor and control the request flow and client access to certain resources
� The token is generated on the server and communicated back to the client
� This avoids duplicate requests, and prevents clients from accessing certain views out of order by returning to previously bookmarked pages
client
token
controller
Usersession
token
request
token
Check client token matches current token in session
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-62 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-63
Instructor Guide
Figure 26-30. Synchronizer Token: Solution (2 of 2) RD8107.5
Notes:
31
Synchronizer token: solution (2 of 2)
Compare with previous user
token from session
Compare with previous user
token from session
Generate and store new token
Generate and store new token
Send responseSend
response Get client token from
request
Get client token from
request
ClientClient
Send error response
Send error response
Tokens match Tokens don’t match
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-64 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-65
Instructor Guide
Figure 26-31. Checkpoint RD8107.5
Notes:
Write down your answers here:
32
Checkpoint1. Why is it important to design a layered architecture?2. What are some JSP design considerations?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-66 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
33
Checkpoint solutions 1. The primary design idea is to decouple the domain from the
presentation and data source requirements. This layering allows reuse of the domain objects across applications. Developers need to design up front how each layer communicates with the adjoining layer. This allows for simultaneous development of each layer, and the distribution of labor.
2. Use the Indirect Model programming model. The JSP page is called indirectly, through a controller (servlet). The sole purpose of the JSP page is to provide a response to the client. There should be no control behavior within the JSP page, and you should minimize the amount of Java code in the JSP page.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-67
Instructor Guide
Figure 26-32. Unit summary RD8107.5
Notes:
34
Unit summary� Having completed this unit, you are able to:
� Identify the important issues involved in server-side application development and testing
� Use layering in the design of a new enterprise application� List some of the benefits and disadvantages of layering� Describe the roles that Java EE elements usually play in a
layered architecture� Explain layered architecture and what each layer does� List Servlet and JSP design considerations� Explain Servlet and JSP patterns and guidelines
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-68 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 26. Best Practices for Server-Side Application Dev. 26-69
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
26-70 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 27. Java EE Packaging and DeploymentEstimated time
00:15
What this unit is about
This unit describes how enterprise applications are packaged according to the Java EE specification.
What you should be able to do
After completing this unit, you should be able to:
• Understand the relationship between components, modules, and enterprise applications
• State the containment hierarchy for Java EE packaging
• Understand the purpose of each type of deployment descriptor
How you will check your progress
Accountability:
• Checkpoint • Discussion
References
http://java.sun.com/javaee/technologies/javaee5.jsp Java Platform, Enterprise Edition 5 (Java EE 5)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-1
Instructor Guide
Figure 27-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Explain the relationship between components, modules, and enterprise applications
�State the containment hierarchy for Java EE packaging�Describe what each type of deployment descriptor is used
for
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Java EE Packaging
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-3
Instructor Guide
Figure 27-2. J2EE Packaging RD8107.5
Notes:
3
Java EE packaging� The Java EE specification defines standard archive formats for
all Java EE components�EJB module
� Packaged in a Java archive (.jar) file
�Web module� Packaged in a Web archive (.war) file
�Application client module� Packaged in a Java archive (.jar) file
�Resource adapter module� Packaged in a resource adapter archive (.rar) file
�Enterprise application� Packaged in an enterprise archive (.ear) file
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Java EE Packaging - Containment Hierarchy
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-5
Instructor Guide
Figure 27-3. J2EE Packaging – Containment Hierarchy RD8107.5
Notes:
Deployment descriptors are identified for each archive type with square-cornered rectangles in this diagram. The resources packaged in each archive type are identified by oval shapes in this diagram.
Each of the nodes of the hierarchy is described in the following slides.
4
web resource
JSP
Servlet
client1.jar
web1.war
res1.rar
EJB
client class
native library
adapter jar
ejb1.jar
Java EE packaging: containment hierarchy
app1.ear
ejb-jar.xml
application-client.xml
web.xml Web resource
JSP
Servlet
ejb1.jar
client1.jar
web1.war
res1.rar
ra.xml
EJB
client class
native library
adapter jar
application.xml
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: EJB Module
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-7
Instructor Guide
Figure 27-4. EJB Module RD8107.5
Notes:
5
EJB module� An EJB module is contained in an EJB JAR file� Several beans may be packaged within a single EJB JAR file� The EJB JAR contains all of the classes required for each EJB
component�The enterprise bean class�The enterprise bean home and component interfaces�The primary key class if the bean is an entity bean
� The deployment descriptor (ejb-jar.xml) contains:�EJB structural information
� Defines the class names, external dependencies, persistent fields and relationships (for CMP beans)
�Application assembly information describing how the EJB components fit into a wider application� Security information and transaction attribute
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Web Module
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-9
Instructor Guide
Figure 27-5. Web Module RD8107.5
Notes:
6
Web module� Web modules (also known as Web applications) are contained
in a Web archive (.war) file� A WAR file will normally contain several servlets, JSP pages
and other Web resources� For example, a Web application may contain HTML files,
graphics files, audio files, and movies� The deployment descriptor (web.xml) contains configuration
information for resources contained in the WAR file� For example, initialization parameters, session
management configuration, servlet declarations and mappings, filter definitions, welcome file list, and error pages
� Security information, tag libraries, and JNDI configuration may also be provided
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Application Client Module
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-11
Instructor Guide
Figure 27-6. Application Client Module RD8107.5
Notes:
7
Application client module� Application clients are contained in .jar files� An application client JAR file contains all of the classes
required for the client to function� The deployment descriptor (application-client.xml)
contains configuration information for the client�The enterprise beans and external resources referenced by
the application client� The mechanism for deployment and installation of the
application client is not specified in the Java EE specification� Java EE product providers may provide an application
launcher that integrates with the application client machine’s native operating system
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement — Next: Resource Adapter Module
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-13
Instructor Guide
Figure 27-7. Resource Adapter Module RD8107.5
Notes:
8
Resource adapter module� Resource adapters are contained in a resource adapter
archive (.rar) file� A RAR file contains:
�Java code for the resource adapter�Utility Java classes for the resource adapter�Platform-dependent native libraries required by the
resource adapter�Help files and documentation
� The deployment descriptor (ra.xml) contains:�General information about the adapter�The class names of the connection factory and
implementation class�Transaction and security information
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information — RARs are used with the Java Connector Architecture to describe communication with an Enterprise Information System.
Transition statement — Next: Enterprise Application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-15
Instructor Guide
Figure 27-8. Enterprise Application RD8107.5
Notes:
9
Enterprise application� Enterprise applications are contained in an enterprise archive
(.ear) file� An EAR file contains one or more Java EE modules
�EJB JAR files, WAR files, application client JAR files, and RAR files
� The enterprise application deployment descriptor (application.xml) contains:�Details about all of the modules packages in the EAR file�Definitions of the security roles for the enterprise
application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details — How are EJB modules packaged?
EJBs are packaged in EJB JAR files.
What is packaged in a WAR file?
Servlets, JSP Taglib Descriptor files, HTML files, JSP files, image and audio files. In addition, the WAR contains the web.xml deployment descriptor file.
How are application client modules packaged?
Application clients are packaged in JAR files.
What is packaged in an EAR file?
Each of the module JAR and WAR files, any dependent JAR or resource files needed by the application components, and the application.xml file. Extension and binding (vendor specific) files are also included in the EAR file.
Why are there IBM bindings?
Bindings map the application to a particular deployment configuration. A particular deployment configuration is vendor specific.
What is the AST?
The Application Server Toolkit (AST) is a tool for creating and modifying application modules (JAR, WAR, and EAR files).
Additional information —
Transition statement — Next: Checkpoint
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-17
Instructor Guide
Figure 27-9. Checkpoint RD8107.5
Notes:
Write down your answers here:
10
Checkpoint1. What is an EAR?2. What are the four types of modules contained in an EAR?3. What are the three types of archives contained in an EAR?4. Which archive type contains servlets and JSP pages?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
11
Checkpoint solutions1. Enterprise Archive2. EAR files can contain the following modules:
• EJB• Web• Resource Adapter• Client Application
3. The three types of archive files are:• WAR (Web archive)• RAR (Resource archive)• JAR (Java archive)
4. WAR
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-19
Instructor Guide
Figure 27-10. Unit summary RD8107.5
Notes:
12
Unit summary� Having completed this unit, you are able to:
�Explain the relationship between components, modules, and enterprise applications
�State the containment hierarchy for Java EE packaging�Describe what each type of deployment descriptor is used
for
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 27. Java EE Packaging and Deployment 27-21
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
27-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 28. Installing an Application in WebSphere Application Server V7.0Estimated time
00:30
What this unit is about
This unit describes the tools used to install applications into WebSphere Application Server, Version 7.0.
What you should be able to do
• Review Java EE application packaging.
• After completing this unit, you should be able to:
- Use the browser-based Administration Console
- Examine the ways that an enterprise application can be installed and modified
- Configure the Application Server and Java EE Resources
How you will check your progress
Accountability:
• Lab exercise
References
http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp WebSphere Application Server Version 7.0 Information Center
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-1
Instructor Guide
Figure 28-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Understand the overall use of the Administration console�Describe the configuration options available�Install an application�Modify existing installed applications�Configure Java EE resources�Save master configuration files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-3
Instructor Guide
Figure 28-2. WebSphere Administration Console RD8107.5
Notes:
3
WebSphere administration console� The Administration Console is browser-based
�It can be used to display configuration information from the XML configuration file.� The server configuration can be modified
�Applications can be controlled. You can:� Install, uninstall, start, and stop them� Display the current state� View application and module names and configuration
�It will also display Deployment descriptors.� Application� EJB modules� Web modules� Application Client modules
�It will allow you to edit some features.� EJB module bindings
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-5
Instructor Guide
Figure 28-3. Administrative Console Overview RD8107.5
Notes:
In the Servers view, right-mouse click the WebSphere Application Server v7.0 at xpbase and select Administration > Run Administrative Console to launch the console.
Specify the following userid and password:
administration
web1sphere
4
Enter http://localhost:9060/ibm/console/
Administrative console overview
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-7
Instructor Guide
Figure 28-4. Administrative Console Navigation Tree RD8107.5
Notes:
5
Administrative console navigation tree� Choose an action:
�Help with activities�Administer application and Web
servers�Administer and install
applications�Administer resource providers
(JDBC or JMS APIs)�Enable and configure security�Configure virtual hosts and
environment variables�Administer the Administration
console�Administer Users and Groups�Configure Performance
Monitoring Infrastructure�Configure Logs and Tracing�Configure SOA elements�Configure UDDI (Universal
Description, Discovery, and Integration) nodes
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-9
Instructor Guide
Figure 28-5. Applications: Console Options RD8107.5
Notes:
To manage an installed Java EE enterprise application, enable the Select check box beside the application name in the list and click a button:
Start attempts to run the application. After the application starts up successfully, the state of the application changes to Started if the application starts up on all deployment targets, otherwise the state changes to Partial Started.
Stop attempts to stop the processing of the application. After the application stops successfully, the state of the application changes to Stopped if the application stops on all deployment targets, otherwise the state changes to Partial Stopped.
Install opens a wizard that helps you deploy an application or a module such as a .jar, .war or .rar file onto a server or a cluster.
6
Applications: console options
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Uninstall deletes the application from the WebSphere Application Server configuration repository and deletes the application binaries from the file system of all nodes where the application modules are installed after the configuration is saved and synchronized with the nodes.Update opens a wizard that helps you update application files deployed on a server. You can update the full application, a single module, a single file, or part of the application. If a new file or module has the same name as a file or module already existing on the server, the new file or module replaces the existing file or module. If the new file or module does not exist on the server, it is added to the deployed application.
Rollout Update sequentially updates an application installed on multiple cluster members across a cluster. After you update an application's files or configuration, click Rollout Update to install the application's updated files or configuration on all cluster members of a cluster on which the application is installed.
Remove File deletes a file from the WebSphere Application Server configuration repository and from the file system of all nodes where the file is installed. If the application or module is deployed on a cluster, after removing a file click Rollout Update to roll out the changes across the entire cluster.
Export accesses the Export Application EAR files page, which you use to export an enterprise application to an EAR file at a location of your choice. Use the Export action to back up a deployed application and to preserve its binding information.
Export DDL accesses the Export Application DDL files page, which you use to export DDL files (Table.ddl) in the EJB modules of an enterprise application to a location of your choice.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-11
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-6. Applications: Installation (1 of 2) RD8107.5
Notes:
7
Applications: installation (1 of 2)� Specify the application (EAR file) or stand-alone module (JAR or
WAR file) to install�If you are installing a Web module, specify the context root
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-13
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-7. Applications: Installation (2 of 2) RD8107.5
Notes:
8
Applications: installation (2 of 2)� Remaining steps involve
�Selecting installation options�Mapping modules to servers�Mapping virtual hosts for Web
modules � Once the application has been
installed, the master configuration must be saved
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-15
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-8. Applications: Modification RD8107.5
Notes:
9
Applications: modification� The Administration Console allows
limited configuration�Changes made through the
Administration Console won’t be reflected in the original .ear file
�You can use Rational Application Developer or the WebSphere Application Server Toolkit to modify the original deployment descriptors� Changes imply reinstalling the
application after modification
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-17
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-9. Servers: Configuration (1 of 2) RD8107.5
Notes:
10
Servers: configuration (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-19
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-10. Servers: Configuration (2 of 2) RD8107.5
Notes:
11
Servers: configuration (2 of 2)� Basic settings are shown at the top of the form� The Runtime tab allows extensive configuration, including
logging, tracing, and the transaction service
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-21
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-11. Resources: Configuration RD8107.5
Notes:
12
Resources: configuration� JMS Providers
�IBM® WebSphere® MQ or others
� JDBC Providers and data sources� Resource Adapters
�Describe J2C access to Enterprise Information Systems
� Asynchronous bean control�Timers and work managers
� Schedulers� Cache management� Mail providers� URL providers
�Allow URLs to be looked up using the JNDI API
� Resource Environment providers�Allow resources to be located
using the JNDI API with logical names
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-23
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-12. Resources: JDBC DataSources RD8107.5
Notes:
13
Resources: JDBC data sources� In addition to basic properties, you can set connection pool
options using the form
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-25
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-13. Resources: JMS Connections RD8107.5
Notes:
14
Resources: JMS connections� You can configure access to JMS resources through the
Administration console
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-27
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-14. Saving Master Configuration RD8107.5
Notes:
15
Saving master configuration� You must save changes to the configuration
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-29
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-15. Checkpoint RD8107.5
Notes:
Write down your answers here:
16
Checkpoint1. Can the Administration console manage web servers?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-31
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
17
Checkpoint solutions1. It can manage Web servers.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Figure 28-16. Unit summary RD8107.5
Notes:
18
Unit summary� Having completed this unit, you are able to:
�Appreciate the overall use of the Administration console�Describe the configuration options available�Install an application�Modify existing installed applications�Configure Java EE resources�Save master configuration files
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 28. Installing an Application in WebSphere Application Server 28-33
Instructor Guide
Instructor notes:
Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
28-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 29. Web Application SecurityEstimated time
00:30
What this unit is about
This unit describes Java EE security support and configuration in Rational Application Developer
What you should be able to do
After completing this unit, you should be able to:
• Apply role-based security to a web application
• Gather roles in the application deployment descriptor
• Configure a web application authentication method
• Set security role references for servlets
• Configure security in the test environment
•
How you will check your progress
Accountability:
• Checkpoint
References
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-1
Instructor Guide
Figure 29-1. Unit objectives RD8107.5
Notes:
2
Unit objectives� After completing this unit, you will be able to:
�Apply role-based security to a Web application�Gather roles in the application deployment descriptor�Configure a Web application authentication method�Set security role references for servlets�Configure security in the test environment
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-3
Instructor Guide
Figure 29-2. Role-based Security RD8107.5
Notes:
The sample bank application defines two roles: an administrator role and a customer role. While administrators can open accounts and check individual account balances, customers can only check on their own account balance. Notice that this scheme does not tie access to users; new customers can join the system and access the banking application without changing the application code.
3
Role-based security� Java EE security uses roles to determine categories of users
that can access a particular enterprise application�A role is an abstract group mapped to a set of security
identities during deployment.�Groups are similar to roles, but apply to all enterprise
projects in the application server.
/accountInfo.jsp
/openAccount.jsp
Web application
Role = Administrator
Role = Customer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-5
Instructor Guide
Figure 29-3. Define Security Roles for Web Applications RD8107.5
Notes:
A security role entry in the Web Deployment Descriptor editor represents the <security-role> tag in the web.xml file. This tag only defines an abstract user role in the Web application. You must create a security role reference to tie this user category to a Web resource, such as a servlet or JSP.
4
Define security roles for Web applications1. Define security roles in the Security details section of the
Web Deployment Descriptor editor� Roles represent categories of users that can access the
Web application
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-7
Instructor Guide
Figure 29-4. Constrain Access Based on Security Role RD8107.5
Notes:
In the web resource collection list, use a URL pattern to define which web resources apply to a particular security constraint. You can also define which HTTP method triggers the security constraint. The authorized roles list which roles are allowed to access the Web resources listed in the security constraint.
Not shown in the screenshot is the user data constraint. This setting specifies whether there is an integrity or confidentiality constraint between the client and the server. In most cases, you must configure secure sockets layer (SSL) to meet an integrity or confidentiality requirement.
5
Constrain access based on security role2. Set Security Constraints
details for the Web application:
a. List which Web resources apply to the security constraint in the Web resource collection
b. Define which roles are authorized to use the Web resource collection in the Authorized Roles
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-9
Instructor Guide
Figure 29-5. Gather Roles in the Enterprise Application RD8107.5
Notes:
Security roles must be gathered in the application deployment descriptor. Using this interface, the deployer maps abstract Java EE security roles to concrete users and groups. The actual list of users and groups are specific to the security package chosen.
6
Gather roles in the enterprise application3. In the Enterprise Application Deployment Descriptor
editor, click the Open WebSphere Bindings link4. Add Security Role and specify name in the details section
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-11
Instructor Guide
Figure 29-6. Web Container Client Authentication RD8107.5
Notes:
Neither basic authentication nor form-based authentication encrypts the user password. Therefore, these forms of authentication should always be used over a secure channel, such as a secure sockets layer (SSL) connection.
In the digest authentication scheme, the server generates an MD5 hash value for the user name, password and URI resource address. Clients create and send an MD5 hash to authenticate itself in a request. Since MD5 creates a unique value that cannot be reversed, other users cannot figure out your password simply from the hash value.
Certificate-based authentication is an alternative to using user name and passwords to authenticate users. A digital certificate uniquely identifies one user from another. Only trusted third parties, known as certificate authorities (CA), issue and sign digital certificates. This scheme prevents individual users from manufacturing their own certificates.
7
Web container client authentication� Authentication methods for a Web application client:
�Basic authentication� Client sends user name and password in the HTTP header using
base64 encoding.
�Form-based authentication� Client sends user name and password in an HTML form� Sent in an HTTP Post request in plain text.
�Digest authentication� Client sends an MD5 (Message-Digest algorithm 5) hash based on the
user name, password, URI resource, and other information.
�Certificate-based authentication� Client uses a digital certificate to uniquely identify itself
– A trusted third-party, known as a certificate authority (CA) issues digital certificates.
– Digital certificates include a unique serial number, identification information, and the user’s public key.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-12 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-13
Instructor Guide
Figure 29-7. Configure Client Authentication Method RD8107.5
Notes:
During HTTP basic authentication, the server sends an authorization request to the client along with the realm name. For users accessing the Web resource using a Web browser, a login dialog box appears. After the user returns the user name and password, the Web browser transmits the information to the server.
In form-based authentication, the specified login page appears on the first time that the user accesses the protected Web resource. If authentication fails, the server returns the specified error page.
Some client authentication methods, such as digest authentication, requires manually editing configuration files in WebSphere Application Server. For complete steps, refer to the redbook SG24-6316-01 (IBM WebSphere Application Server V6.1 Security Handbook ).
8
Configure client authentication method1. In the Web Deployment Descriptor, add Login
Configuration item and specify the following details.a. For basic authentication, enter an arbitrary realm nameb. For form authentication, specify both a Login page and
an Error page
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-14 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-15
Instructor Guide
Figure 29-8. Declarative and Programmatic Security RD8107.5
Notes:
The discussion on Web application security dealt with declarative security up to this point. Declarative security separates business logic from security information, making applications more portable and robust. However, there are some cases in which the application needs to know the security context of a particular request. Using the sample bank application, the account page might need to retrieve the account balance based on the user name.
9
Declarative and programmatic security� Web application security configured using a declarative model� Web applications can view security information
programmatically� The following three methods from HttpServletRequest
provides information on the security context:� getRemoteUser()
– Returns the user name that the client used for authentication– Returns null if no user is authenticated
� isUserInRole(String name)
– Returns true if the remote user is granted the specified security role
– If the remote user is not granted the specified role, or if no user is authenticated, it returns false
� getUserPrincipal()
– Returns the java.security.Principal object containing the remote user name
– If no user is authenticated, it returns null
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-16 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-17
Instructor Guide
Figure 29-9. Define Security Role References RD8107.5
Notes:
The best practice is to use security role references instead of referring to an actual security role when using programmatic security calls. For example, instead of calling httpServletRequest.isUserInRole(“Administrator”), replace the role name of “Administrator” with “Manager”. Define a security role reference for the Administrator role and name it as Manager. This scheme allows the deployer to change the security information in the deployment descriptor without affecting the compiled Web application.
10
Define security role references� Use security role references to avoid hard-coding Java EE
security role names into programmatic security calls� Reference acts as an alias to the actual security role name� Per servlet setting, set in the Security Role Reference list
within the Servlets section in the Web Deployment Descriptor
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-18 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-19
Instructor Guide
Figure 29-10. Enterprise Application Security Overview RD8107.5
Notes:
Java 2 Security is a programmatic security model introduced with J2SE 1.2. Java EE security does not require Java 2 Security; the two systems can co-exist in an enterprise application.
11
Enterprise application security overview� WebSphere Application Server is built upon several layers of
security:� The operating system protects WebSphere configuration
files, and provides user authentication when using the local OS user registry
� The Java Virtual Machine (JVM) provides standard Java security
� Java™ 2 Security builds upon standard Java security� Fine-grained access control� Configurable security policy� Security checks for all Java applications
� Java™ EE Security provides standard, container-level security� Insulates enterprise applications from the actual security
implementation� Classifies clients into roles, each with different access levels for a
given resource
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-20 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-21
Instructor Guide
Figure 29-11. WebSphere Environment Security Layers RD8107.5
Notes:
This module focuses on the security layers most likely used by Web applications: application level and transport level security. Application level security covers role-based access provided by Java EE and WebSphere security. Transport level security covers authentication mechanisms and encryption layers.
12
WebSphere environment security layers
Platform SecurityOperating System
Java SecurityJava Virtual Machine
Java 2 Security
JCE JAAS JSSE
Java EE SecurityJava EE Security
WebSphere Security
Transport SecurityHTTP IIOP LDAP
Client SecurityClient application / external component
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-22 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-23
Instructor Guide
Figure 29-12. Security in WebSphere (1 of 2) RD8107.5
Notes:
13
Security in WebSphere (1 of 2)� Security is now enabled by default� Managed in the administrative console
� You can set it manually, or you can use the Security Configuration wizard
� You can generate a Security Configuration report to detail environment
� Java EE security� Global security provides Java EE security
� Java 2 security� Provides additional security beyond Java EE security
� Administrative console security� Users must enter user name and password to access the
Administrative console
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-24 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-25
Instructor Guide
Figure 29-13. Security in WebSphere (2 of 2) RD8107.5
Notes:
14
Security in WebSphere (2 of 2)� Authentication of HTTP clients
�Enforces basic, digest, form, or certificate-based authentication
� Role-based authorization checks for Web resources�Enforces security constraints set in the Web deployment
descriptor� Secure Sockets Layer (SSL)
�Provides security that has a confidentiality security restraint for Web application resources
� V6.1 also supports Simple and Protected GSS-API Negotiation (SPNEGO) �Allows single sign-on from a Windows desktop browser that
supports SPNEGO authentication
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-26 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-27
Instructor Guide
Figure 29-14. Manage Security in WebSphere RD8107.5
Notes:
15
Manage security in WebSphere� In the WebSphere Administration console, open Security �
Secure administration, applications, and infrastructure� Run the Wizard� Restart server
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-28 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-29
Instructor Guide
Figure 29-15. Checkpoint RD8107.5
Notes:
Write down your answers here:
16
Checkpoint1. What types of security constraints can you set to a Web
resource collection?2. What is the purpose of gathering security roles in the
application deployment descriptor?3. What is the purpose of creating a security role reference?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-30 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
17
Checkpoint solutions1. There are two types of security constraints that you can set:
a) Authorized users determine which roles are allowed to access the named resources.
b) User data constraints determine the confidentiality and integrity requirements for the communication between the client and server.
2. Gathering security role references collects all of the security roles into the application deployment descriptor. After completing this step, you can map security roles to actual users and groups.
3. A security role reference avoids hard-coding a role name into the Web application code. This idea is similar to how resource references avoid the need to hard-code a JNDI lookup name into code.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-31
Instructor Guide
Figure 29-16. Unit summary RD8107.5
Notes:
18
Unit summary� Having completed this unit, you are able to:
� Explain the difference between declarative and programmatic security models
� Set security constraints to Web resources� Create security role references for servlets� Set the Web client authentication method� Configure security from the Administration console
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-32 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 29. Web Application Security 29-33
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
29-34 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Unit 30. Course SummaryEstimated time
00:15
What this unit is about
This unit summarizes the course.
What you should be able to do
After completing this unit, you should be able to state some valuable resources for more information and education.
How you will check your progress
Accountability:
• Discussion
References
http://www.ibm.com/services/learning
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 30. Course Summary 30-1
Instructor Guide
Figure 30-1. What This Course Was About RD8107.5
Notes:
2
What this course was about� Developing Servlets and JSP pages and discussing best
practices� Developing JavaBeans components (beans)� Developing JSP Custom tags and tag files� Developing Servlet Filters and Listeners� Integrating Servlets, JSP pages, and beans to construct an
application with a model-view-controller (MVC) design pattern� Using IBM Rational Application Developer � Using Java EE security to secure Web applications� Integration Testing in IBM WebSphere Application Server
V7.0
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
30-2 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 30. Course Summary 30-3
Instructor Guide
Figure 30-2. Resources RD8107.5
Notes:
3
Resources� Web cages
�WebSphere family� http://www.ibm.com/websphere
�WebSphere developerWorks� http://www.ibm.com/
developerworks/websphere
�Java specifications� http://java.sun.com/j2ee� http://java.sun.com/products/ servlet� http://java.sun.com/products/jsp� http://java.sun.com/products/jndi
�World Wide Web consortium� http://www.w3c.org
� Training�IBM Learning Services
� http://www.ibm.com/services/learning
�ITSO Redbooks:� http://www.redbooks.ibm.com
� WebSphere certification�http://www.ibm.com/certify/certs
/ws_index.shtml� News groups
�ibm.software.websphere. application-server
�ibm.software.websphere.studio�ibm.software.websphere.studio.
application-site-developer
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
30-4 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 30. Course Summary 30-5
Instructor Guide
Figure 30-3. Other WebSphere Courses RD8107.5
Notes:
4
Other Rational Application Developer courses� RD815: Mastering Web Application Development with Rational
Application Developer v7.5� RD793: Mastering EJB Development with Rational Application
Developer v7� RD795: Mastering JSF Development with Rational Application
Developer v7
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
30-6 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 30. Course Summary 30-7
Instructor Guide
Figure 30-4. Finally RD8107.5
Notes:
5
Finally� Please provide feedback via course evaluation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
30-8 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
Instructor GuideV5.2
Uempty
Instructor notes:Purpose —
Details —
Additional information —
Transition statement —
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 2009 Unit 30. Course Summary 30-9
Instructor Guide
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
30-10 Mastering Servlet and JSP Development with Rational Application © Copyright IBM Corp. 2009
V5.2
backpg
Back page