You are on page 1of 502

Beyond CGI: Developing Java Servlets

SL-310

Student Guide With Instructor Notes

Enterprise Services
MS BRM01-209
500 Eldorado Blvd.
Broomfield, Colorado 80021
U.S.A.

Part Number 805-5989-01


Revision A, October 1998
Copyright © 1998 Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying,
distribution, and decompilation. No part of this product or document may be reproduced in any form by any means
without prior written authorization of Sun and its licensors, if any.
Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.
Sun, Sun Microsystems, the Sun Logo, Java, JavaBeans, Java Web Server, JavaServer, JavaServer Pages, JDBC, JavaScript,
JDK, and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc.
in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun
Microsystems, Inc.
Netscape Navigator is a trademark of Netscape Communications Corporation.
UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.
The OPEN LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees.
Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user
interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface,
which license also covers Sun licensees who implement OPEN LOOK GUIs and otherwise comply with Sun written
license agreements.
RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-
14(g) (2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015 (b)(6/95) and DFAR 227.7202-3(a).
DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS,
AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH
DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Please
Recycle
Contents
About This Course.................................................................................... xiii
Course Overview .............................................................................. xiv
Course Map........................................................................................ xvi
Module-by-Module Overview ...................................................... xvii
Course Objectives.............................................................................. xxi
Skills Gained by Module................................................................. xxii
Guidelines for Module Pacing ..................................................... xxiii
Topics Not Covered....................................................................... xxiv
How Prepared Are You?................................................................. xxv
Introductions .................................................................................. xxvi
How to Use Course Materials ..................................................... xxvii
Course Icons and Typographical Conventions .......................... xxix
Icons ..........................................................................................xxix
Typographical Conventions ..................................................xxxi
Notes to the Instructor................................................................... xxxii
Philosophy ..............................................................................xxxii
Course Tools ...........................................................................xxxii
Instructor Setup Notes ................................................................ xxxvi
Purpose of This Guide......................................................... xxxvi
Minimum Resource Requirements.................................... xxxvi
Assumptions About the Lab.............................................. xxxvii
Setting up for an SL310 Class ................................................... xxxviii
Student Workstations ........................................................ xxxviii
Server Machine................................................................... xxxviii
Projection System and Workstation ................................ xxxviii
Course Files.......................................................................................... xl
Configuring the Classroom ............................................................ xlii
Student Workstations .............................................................. xlii
Server Machine (if Applicable) ............................................. xlvi
Servlet Basics ..............................................................................................1-1
Relevance............................................................................................ 1-2
Objectives ........................................................................................... 1-3
Common Gateway Interface (CGI)................................................. 1-4

iii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Overview ....................................................................................1-4
Example Uses.............................................................................1-4
CGI Request and Response.............................................................. 1-6
Request and Response Mechanism ........................................1-6
CGI and HTTP...........................................................................1-7
An Example HelloWorld CGI Script ............................................. 1-8
Script Code.................................................................................1-8
Setting Content Type ................................................................1-9
Returning a Response.............................................................1-10
Invoking the Example CGI Script.........................................1-11
Web Server and Common Gateway Interface Support ............. 1-12
What Is a Servlet?............................................................................ 1-13
Definition..................................................................................1-13
Example Uses...........................................................................1-14
Servlet Request and Response....................................................... 1-15
Request and Response Overview .........................................1-15
HTTP and Servlets ..................................................................1-17
An Example HelloWorld Servlet ................................................. 1-18
Servlet Code.............................................................................1-19
HttpServlet ...............................................................................1-20
The service Method .............................................................1-21
Setting Content Type ..............................................................1-22
Returning a Response.............................................................1-24
Writing Exceptions to Log Files ............................................1-25
Invoking the Example Servlet ....................................................... 1-26
Invocation URL .......................................................................1-26
servlet/ Versus servlets/................................................1-27
Web Server Servlet Support .......................................................... 1-28
Review of Servlet Basics................................................................. 1-29
Exercise: Developing a Simple HTTP Servlet ............................. 1-31
Preparation...............................................................................1-31
Tasks .........................................................................................1-32
Exercise Summary...................................................................1-35
Check Your Progress ...................................................................... 1-36
Think Beyond .................................................................................. 1-37
Forms Processing With Servlets..............................................................2-1
Relevance............................................................................................ 2-2
Objectives ........................................................................................... 2-3
A Basic Form Solution ...................................................................... 2-4
An Example HTML Form ................................................................ 2-5
The <FORM> Tag .........................................................................2-7
The <FORM> Tag .......................................................................2-11
The <INPUT> Tag.....................................................................2-12
An Example Form-Processing Script ........................................... 2-13
Script Code...............................................................................2-14

iv Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Setting Content Type ..............................................................2-15
Reading the Request ...............................................................2-15
Parsing the Request ................................................................2-16
Returning a Response.............................................................2-18
Invoking the Example Form-Processing Script .......................... 2-19
Forms and Servlets.......................................................................... 2-20
An Example Form-Processing Servlet ......................................... 2-21
Servlet Code.............................................................................2-21
HTTPServlet Service Methods ..............................................2-22
Setting Content Type ..............................................................2-25
Parsing the Request ................................................................2-26
CGI Variables and Equivalent Servlet APIs........................2-29
Returning a Response.............................................................2-30
Displaying Information About a Servlet .............................2-31
Review of Form Servlets ................................................................ 2-33
Exercise: Developing Form-Processing Servlets......................... 2-36
Preparation...............................................................................2-36
Tasks .........................................................................................2-37
Exercise Summary...................................................................2-41
Check Your Progress ...................................................................... 2-42
Think Beyond .................................................................................. 2-43
Servlet Life C ycle ......................................................................................3-1
Relevance............................................................................................ 3-2
Objectives ........................................................................................... 3-3
Servlet Life Cycle .............................................................................. 3-4
Loading and Instantiating a Servlet ............................................... 3-5
Class Loaders.............................................................................3-5
Servlets on the CLASSPATH.......................................................3-6
Servlets in server_root/servlets/..........................................3-6
Remote Servlets .........................................................................3-6
The init Method .............................................................................. 3-7
Overview ....................................................................................3-7
An Example init Method.......................................................3-8
Configuring Initialization Parameters .................................3-11
The service Method ..................................................................... 3-12
ServletRequest.....................................................................3-12
ServletResponse ..................................................................3-13
Concurrency Issues.................................................................3-13
Multithreaded-Safe Servlets ..................................................3-14
Multithreaded-Hot Servlets...................................................3-16
SingleThreadModel..............................................................3-17
The destroy Method ..................................................................... 3-18
Overview ..................................................................................3-18
Handling Service Threads at Servlet Termination.............3-21
Tasks in Handling Threads....................................................3-22

v
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
An Example of Handling Service Threads ..........................3-23
Review of Servlet Life Cycle.......................................................... 3-26
Exercise: Modifying the Form-Processing Servlet ..................... 3-29
Preparation...............................................................................3-29
Tasks .........................................................................................3-30
Exercise Summary...................................................................3-34
Check Your Progress ...................................................................... 3-35
Think Beyond .................................................................................. 3-36
Database Access .........................................................................................4-1
Relevance............................................................................................ 4-2
Objectives ........................................................................................... 4-3
Distributed Models ........................................................................... 4-4
Two-Tier (Client/Server) .........................................................4-4
Multi-Tier ...................................................................................4-5
Distributed Java Technologies ........................................................ 4-7
Java Database Connectivity (JDBC)................................................ 4-8
Overview ....................................................................................4-8
An Example Database Servlet .................................................4-9
Loading the Database Driver ................................................4-12
Establishing a Connection to the Database .........................4-13
Creating and Executing a Query ..........................................4-14
Parsing and Displaying the Results .....................................4-15
Closing the Connection ..........................................................4-16
JDBC and Servlets ........................................................................... 4-17
Connection Pools............................................................................. 4-18
Overview ..................................................................................4-18
Items to Consider ....................................................................4-19
Implementing a Connection Pool ................................................. 4-20
A Connection Pool Client ......................................................4-21
An Example Connection Pool Client Servlet ......................4-23
The ConnectionPool API ............................................................. 4-24
The ConnectionPool Constructor.......................................4-25
The addConnection Method ................................................4-26
The getNewConnection Method..........................................4-27
The getConnection Method ................................................4-28
The releaseConnection Method .......................................4-30
The closeAll Method ...........................................................4-32
Review of Database Access............................................................ 4-33
Exercise: Enhancing a Database Servlet....................................... 4-35
Preparation...............................................................................4-35
Tasks .........................................................................................4-36
Exercise Summary...................................................................4-38
Check Your Progress ...................................................................... 4-39
Think Beyond .................................................................................. 4-40
RMI and CORBA/IDL...............................................................................5-1

vi Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Relevance............................................................................................ 5-2
Objectives ........................................................................................... 5-3
RMI...................................................................................................... 5-4
RMI Client, Server and Registry Interaction................................. 5-6
Implementing a Basic RMI Server .................................................. 5-8
Implementing a Basic RMI Client................................................... 5-9
Installing and Invoking the Server, Client, and RMI
Registry.......................................................................................... 5-10
RMI and Servlets ............................................................................. 5-11
An Example RMI Servlet Solution........................................5-12
An Example RMI Server ........................................................5-13
An Example RMI Client .........................................................5-18
An Example RMI Applet .......................................................5-23
Java IDL ............................................................................................ 5-26
Overview ..................................................................................5-26
Java IDL and Servlets .............................................................5-27
Comparing RMI and CORBA/IDL ......................................5-27
Review of Java RMI and IDL......................................................... 5-28
Exercise: Configuring and Invoking the RMI Example ............ 5-29
Preparation...............................................................................5-29
Tasks .........................................................................................5-30
Exercise Summary...................................................................5-32
Check Your Progress ...................................................................... 5-33
Think Beyond .................................................................................. 5-34
Persistent State in HTTP Servlets...........................................................6-1
Relevance............................................................................................ 6-2
Objectives ........................................................................................... 6-3
Benefits and Limitations of Statelessness in the HTTP
Protocol............................................................................................ 6-4
Cookies ............................................................................................... 6-7
Programming With Cookies....................................................6-8
Setting a Cookie.........................................................................6-9
Retrieving a Cookie ................................................................6-10
Sessions............................................................................................. 6-11
The HttpSession Interface ...................................................6-12
Example ....................................................................................6-13
Additional Guidelines ............................................................6-22
Tying a Session to a Browser......................................................... 6-24
Cookies .....................................................................................6-24
URL Rewriting.........................................................................6-25
Cookies and Sessions Compared.................................................. 6-26
Review of Cookies and Sessions ................................................... 6-28
Exercise: Developing a Web Shopping Solution ........................ 6-31
Preparation...............................................................................6-31
Tasks .........................................................................................6-32

vii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Exercise Summary...................................................................6-38
Check Your Progress ...................................................................... 6-39
Think Beyond .................................................................................. 6-40
Time-Extended Connections....................................................................7-1
Relevance............................................................................................ 7-2
Objectives ........................................................................................... 7-3
What Is a Time-Extended Connection? ......................................... 7-4
Implementation Options.................................................................. 7-5
Client Pull and Server Push.....................................................7-5
Efficiency of Client Pull and Server Push..............................7-6
HTML and Dynamic Updates......................................................... 7-7
Java Technology and Dynamic Updates ....................................... 7-8
Continuous or Transient TCP Connections .................................. 7-9
User Datagram Protocol................................................................. 7-11
Broadcast and Multicast Connections.......................................... 7-13
Review of Time-Extended Connections ...................................... 7-15
Exercise: Developing a Transaction Monitor .............................. 7-17
Preparation...............................................................................7-17
Tasks .........................................................................................7-18
Exercise Summary...................................................................7-22
Check Your Progress ...................................................................... 7-23
Think Beyond .................................................................................. 7-24
Servlet Security...........................................................................................8-1
Relevance............................................................................................ 8-2
Objectives ........................................................................................... 8-3
Major Threats to Web Server Security ........................................... 8-4
Authentication and Authorization ................................................ 8-6
Definition....................................................................................8-6
Authentication Mechanism Overview...................................8-7
Authorization Process Overview............................................8-7
Types of HTTP Authentication ....................................................... 8-8
Overview ....................................................................................8-8
Basic Authentication.................................................................8-9
Digest Authentication ............................................................8-10
SSL Server Authentication.....................................................8-10
Security Realms ............................................................................... 8-12
Definition..................................................................................8-12
Realms Within Java Web Server ...........................................8-13
Basic HTTP Authentication In-Depth .......................................... 8-16
The Seven Steps of Basic HTTP Authentication ......................... 8-18
Step One: Browser Sends URL ..............................................8-18
Step Two: Server Determines Whether Page Is
Protected................................................................................8-18
Step Three: Web Server Checks for Non-Null
Authorization Header, and Sends Challenge ..................8-20

viii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Step Four: Browser Interprets 401 Error as Challenge ......8-21
Step Five: Dialog Box Prompts for User Name and
Password ...............................................................................8-21
Step Six: Browser Returns Encoded Authentication
Information ...........................................................................8-21
Step Seven: Server Validates Authentication
Information, Returns Page..................................................8-24
Implementing Basic Authentication in a Servlet ........................ 8-25
An Example Basic Authentication Servlet...........................8-26
Steps in Example Basic Authentication Servlet ..................8-28
Examples of Server-Independent Validation.............................. 8-29
Additional Security Features Java Web Server........................... 8-31
Secure Administration and Servlet Sandboxing ................8-31
Secure Administration With SSL ..........................................8-32
Servlet Sandbox .......................................................................8-34
Servlet Types.................................................................................... 8-37
RemoteUser Property..................................................................... 8-39
Overview ..................................................................................8-39
Checking the RemoteUser Property.....................................8-40
Sanity Checking............................................................................... 8-41
Review of Servlet Security ............................................................. 8-42
Exercise: Basic and Certificate Authentication Servlets ............ 8-44
Preparation...............................................................................8-44
Tasks .........................................................................................8-45
Exercise Summary...................................................................8-49
Check Your Progress ...................................................................... 8-50
Think Beyond .................................................................................. 8-51
Servlet Beans...............................................................................................9-1
Relevance............................................................................................ 9-2
Objectives ........................................................................................... 9-3
What Is JavaBeans? ........................................................................... 9-4
Functionality of Beans ...................................................................... 9-5
What Is a Servlet Bean? .................................................................... 9-6
Definition....................................................................................9-6
An Example Servlet Bean.........................................................9-7
Setting Header Information.....................................................9-9
get and set Accessor and Mutator Methods.....................9-11
Servlet Beans Persistence ............................................................... 9-13
Implementing java.io.Serializable .............................9-13
Writing to a Serialization File................................................9-13
Packaging Servlet Beans................................................................. 9-16
Servlet Bean Instantiation .............................................................. 9-17
Class Loader for Deserializing Beans Files .........................9-17
Locations for Servlet Beans....................................................9-17
Automatic Reloading of Servlet Beans ................................9-18

ix
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Invoking Servlet Beans................................................................... 9-19
Invoking Servlet Beans Using a URL ...................................9-19
An Example of Invoking a Servlet Bean Using a URL ......9-20
Invoking Servlet Beans................................................................... 9-22
Review of Servlet Beans ................................................................. 9-23
Exercise: Creating a Servlet Bean.................................................. 9-25
Preparation...............................................................................9-25
Tasks .........................................................................................9-26
Exercise Summary...................................................................9-32
Check Your Progress ...................................................................... 9-33
Think Beyond .................................................................................. 9-34
Dynamic Web Content............................................................................10-1
Relevance.......................................................................................... 10-2
Objectives ......................................................................................... 10-3
Generating Dynamic Content ....................................................... 10-4
CGI print Statements.................................................................... 10-5
Servlet println Statements .......................................................... 10-6
Servlet println and Perl print Statements............................... 10-7
JavaServer Pages ............................................................................. 10-8
Definition..................................................................................10-8
An Example JavaServer Page ..............................................10-10
JavaServer Pages Syntax .............................................................. 10-11
Directives........................................................................................ 10-12
Language ................................................................................10-12
Method....................................................................................10-13
Import .....................................................................................10-13
Implements ............................................................................10-13
Extends ...................................................................................10-14
Declarations ................................................................................... 10-15
Definition................................................................................10-15
An Example JavaServer Page Declaration.........................10-16
Scriptlets ......................................................................................... 10-17
Definition................................................................................10-17
request ..................................................................................10-18
response................................................................................10-18
out...........................................................................................10-18
in .............................................................................................10-18
Expressions .................................................................................... 10-19
Definition................................................................................10-19
An Example JavaServer Page Expression..........................10-19
Additional Guidelines .................................................................. 10-20
The <BEAN> Tag ............................................................................. 10-22
Definition................................................................................10-22
An Example JavaServer Page Using the <BEAN> Tag ......10-23
Declaring a Bean............................................................................ 10-25

x Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
name.........................................................................................10-25
varname..................................................................................10-26
type.........................................................................................10-26
introspect ...........................................................................10-26
create ....................................................................................10-27
scope ......................................................................................10-27
beanName................................................................................10-28
PageCompileServlet...................................................................... 10-29
An Example JavaServer Page ..............................................10-31
An Example Servlet Created From a JavaServer Page ....10-32
Creating a Servlet From a JavaServer Page.......................10-34
Review of JavaServer Pages......................................................... 10-35
Exercise: Creating JavaServer Pages .......................................... 10-39
Preparation.............................................................................10-39
Tasks .......................................................................................10-40
Exercise Summary.................................................................10-46
Check Your Progress .................................................................... 10-47
Think Beyond ................................................................................ 10-48
CGI, HTTP, and Servlets .........................................................................A-1
HTTP MIME Types.......................................................................... A-2
Using Java Web Server............................................................................. B-1
Supported Platforms........................................................................ B-2
Prerequisites...................................................................................... B-3
Hardware .................................................................................. B-3
Software..................................................................................... B-3
Installation......................................................................................... B-5
Solaris......................................................................................... B-5
Running the Java Web Server ........................................................ B-6
Solaris......................................................................................... B-6
Displaying the Default Home Page............................................... B-7
Launching the Administration Applet ......................................... B-8
Adding a Servlet to Java Web Server ............................................ B-9
Adding Initialization Parameters ................................................ B-12
Configuring a Remote Servlet ...................................................... B-13
Invoking a Servlet From Within an HTML Form...................... B-15
Server-Side Includes (SSI)............................................................. B-16
Overview ................................................................................. B-16
Usage and Implications......................................................... B-16
Standard Server-Side Include Tags ..................................... B-16
Server-Side Include Tags for Servlets ................................. B-17
Servlet Aliases................................................................................. B-19
Overview ................................................................................. B-19
Adding a Servlet Alias .......................................................... B-19
Arguments .............................................................................. B-21
Servlet Chaining............................................................................. B-22

xi
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Overview ................................................................................. B-22
Servlet Chaining and Servlet Aliases .................................. B-22
Servlet Chaining and MIME Types ..................................... B-22
Enabling Servlet Chaining .................................................... B-24
Servlet Context ............................................................................... B-26
Using the Documentation............................................................. B-27
Additional References ................................................................... B-28
JSERV-INTERST...................................................................... B-28
Other Servlet References ....................................................... B-29
CGI Variables and Servlet API ..............................................................C-1
HttpServletRequest Methods .................................................... C-2
Additional Methods......................................................................... C-4
Java Socket Programming .......................................................................D-1
IP Addressing ................................................................................... D-2
Network Address.....................................................................D-2
Subnet Mask..............................................................................D-2
Determining the Local Subnet Mask.....................................D-3
Network Classes.......................................................................D-3
Name Services .................................................................................. D-4
Port Numbers ................................................................................... D-6
Comparison of Protocols................................................................. D-7
Java Socket APIs............................................................................... D-8
TCP Sockets...............................................................................D-8
UDP Sockets..............................................................................D-9
Multicast Sockets....................................................................D-11
Replying to Broadcast and Multicast Data
Transmissions ......................................................................D-11
Glossary ......................................................................................... Glossary-1
Index .....................................................................................................Index-1

xii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
About This Course

Course Goal
The primary goal of Beyond CGI: Developing Java Servlets is to establish
an understanding of servlet development, in contrast to common
gateway interface (CGI), and create several servlet solutions.You
should be able to identify how these solutions fit into your own
Internet and intranet needs.
✓ You should use this module to get the students excited about this course.

✓ With regard to the overheads: To avoid confusion among the students, it is very important
to tell them that the page numbers on the overheads have no relation to the page numbers
in their course materials. They should use the title of each overhead as a reference.

✓ The strategy provided by the “About This Course” is to introduce students to the course
before they introduce themselves to you and one another. By familiarizing them with the
content of the course first, their introductions will have more meaning in relation to the
course prerequisites and objectives.

✓ Use this introduction to the course to determine how well students are equipped with the
prerequisite knowledge and skills. The pacing chart on page xxiii enables you to
determine what adjustments you need to make in order to accommodate the learning
needs of students.

xiii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Overview

Servlets are Java™ programming objects that extend the functionality


of server-based services such as a hypertext transfer protocol (HTTP)
or secure Web service. Servlets are a robust replacement for CGI
scripts. This course covers the development of servlets using the
servlet application programming interface (API) and servlet-related
functionality found within many Web servers.

The majority of this course focuses on how to develop servlets to solve


real-world business problems such as forms processing, dynamic Web
content, distributed computing, collaborative computing, and security.
Servlet development issues include connection management, servlet
security, multithreaded servlets, and servlet Beans.

xiv Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Overview

This course uses the Java Web Server™ for servlet development and
deployment. This course also introduces the major servlet-related
features of the Java Web Server, including server-side includes and
servlet aliasing.
✓ Other servlet platforms may be available for use in future releases of this course. Java
Web Server was chosen, for the initial release of this course, as it provides a wide variety
of servlet/Web server functionality. Please refer students to Appendix B and the Java Web
Server documentation for information on using Java Web Server.

About This Course xv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Map

Each module begins with a course map that enables you to see what
you have accomplished and where you are going in reference to the
course goal. A complete map of this course is shown below.

Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

xvi Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Module-by-Module Overview

● Module 1 - Servlet Basics

This module provides an introduction to servlet development by


examining and comparing a simple HelloWorld CGI script and
servlet.

Lab exercises: Develop a simple HTTP servlet.

● Module 2 – Forms Processing With Servlets

This module builds upon basic servlet development through the


introduction of HTTP request handling and the creation of a form-
processing servlet.

Lab exercises: Develop a form-processing servlet.

About This Course xvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Module-by-Module Overview

● Module 3 – Servlet Life Cycle

This module provides an in-depth discussion of a servlet’s life


cycle. This discussion includes various development issues relative
to each stage in the life cycle.

Lab exercises: Modify the form-processing servlet to accept a file


name and directory as initialization parameters. Ensure that the
form-processing servlet handles long-running threads.

● Module 4 – Database Access

Database access is one of the primary uses of CGI scripts and


servlets. This module discusses using a JDBC™ connection pool to
optimize database access times between a Web browser and Web
server.

Lab exercises: Implement a connection pool within a servlet for


database access.

● Module 5 – RMI and CORBA/IDL

This module describes how common object request broker


architecture/interface definition language (CORBA/IDL) and
remote method invocation (RMI) are implemented within servlets.

Lab exercises: Run the CORBA/IDL and RMI examples.

xviii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Module-by-Module Overview

● Module 6 – Persistent State in HTTP Servlets

Persistent state allows information to be kept over time, and


shared between a series of Web pages sent by one server to the
same browser. This is central to many shopping applications.

Lab exercises: Develop a login and a purchase servlet which create


and share a session.

● Module 7 – Time-Extended Connections

A servlet might need to pass information to a browser on a


continuous basis. This functionality requires a special “time-
extended” connection. This module discusses various time-
extended connection options.

Lab exercises: Develop a transaction monitoring servlet using user


datagram protocol (UDP) broadcast.

About This Course xix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Module-by-Module Overview

● Module 8 – Servlet Security

This module provides an overview of Java Web Server and servlet


security. It is designed to provide you with enough information to
enable a secure Java Web Server and servlet environment. Items
discussed include: basic authentication, access control lists (ACLs),
and realms.

Lab exercises: Create a servlet that uses basic authentication to log


in to a Web server.

● Module 9 – Servlet Beans

The JavaBeans™ architecture can be used to create server-side


servlet components. This module addresses the issues involved
with creating a servlet that is also a Bean.

Lab exercises: Develop a servlet Bean that utilizes standard Beans


functionality such as introspection and serialization. Alter a servlet
Bean to be persistent, allowing it to save its state upon servlet
termination.

● Module 10 – Dynamic Web Content (optional)

This module discusses JavaServer™ Pages™, an integrated


solution for generating and returning dynamic Web page content
to a client (browser).

Lab exercises: Create a simple JavaServer page that requests form


data, submits the data, computes two values from the data, and
displays the computed values. Create a JavaServer page that sends
the computed values to an ImageTableBean to display a user-
definable grid of images on a Web page.

Module 10 is an optional module. Survey students to see how many of


them are interested in this module as it covers pre-release software
and is not as closely related to servlet development as are the
remainder of the modules in this course.

xx Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Objectives

Upon completion of this course, you should be able to

● Develop a simple hypertext transfer protocol (HTTP) servlet.

● Develop a form-processing servlet.

● Modify a form-processing servlet to accept a file name and


directory as initialization parameters.

● Modify a database access servlet to use a connection pool.

● Evaluate RMI and CORBA/IDL servlet solutions.

● Create part of a Web shopping servlet that uses session tracking to


keep track of customer information.

● Develop a Web-monitoring servlet using a time-extended


connection.

● Develop a servlet that implements basic authentication.

● Develop a servlet Bean that utilizes introspection and serialization.

● Create a JavaServer page used to generate a grid of images on a


Web page.

About This Course xxi


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Skills Gained by Module

The skills for Beyond CGI: Developing Java Servlets are shown in the first
column of the matrix below. The black boxes indicate the main
coverage for a topic; the gray boxes indicate the topic is briefly
discussed.

Module

Skills Gained 1 2 3 4 5 6 7 8 9 10

Develop a simple HTTP servlet.


Develop a form-processing servlet.
Modify a form-processing servlet to accept a file
name and directory as initialization parameters.
Modify a database access servlet to use a
connection pool.
Evaluate RMI and CORBA/IDL servlet solutions.
Create part of a Web shopping servlet that uses
session tracking to keep track of customer
information.
Develop a Web-monitoring servlet using a time
extended connection.
Develop a servlet that implements basic
authentication.
Develop a servlet Bean that utilizes introspection
and serialization.
Create a JavaServer page used to generate a grid
of images on a Web page.

✓ Refer students back to this matrix as you progress through the course to show them the
progress they are making in learning the skills advertised for this course.

xxii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Guidelines for Module Pacing

The table below provides a rough estimate of pacing for this course.

Module Day 1 Day 2 Day 3

About This Course AM


Servlet Basics AM
Forms Processing With Servlets AM/PM
Servlet Life Cycle PM
Database Access AM
RMI and CORBA/IDL AM/PM
Persistent State in HTTP Servlets PM
Time-Extended Connections AM
Servlet Security AM
Servlet Beans PM
Dynamic Web Content PM

About This Course xxiii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Topics Not Covered

This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services:

● Object-oriented concepts – Covered in OO-100: Object-Oriented


Technology and Concepts.

● Object-oriented design and analysis – Covered in OO-120: Object-


Oriented Design and Analysis.

● Java programming language constructs – Covered in: SL-110 Java


Programming for Non-Programmers or SL-275: Java Programming.

● System administration concepts – Covered in SA-135: Solaris 2.X


Administration Essentials and SA-285: Solaris 2.X System
Administration.

Refer to the Sun Educational Services catalog for specific information


and registration.

xxiv Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
How Prepared Are You?

To be sure you are prepared to take this course, can you answer the
following questions in the affirmative?

● Do you have experience using Web browsers?

● Do you have experience programming in the Java language; and


does your experience include developing applets, and working
with thread and security APIs?

● Are you comfortable learning new APIs?

● Do you excel in courses that use a hands-on approach to


programming?
✓ If any students indicate they cannot do the above, meet with them at the first break to
decide how to proceed with the class. Do they want to take the class at a later date? Is
there some way to get the extra help needed during the week?

✓ It might be appropriate here to recommend resources from the Enterprise Services


catalog that provide training for topics not covered in this course.

About This Course xxv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Introductions

Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.

xxvi Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
How to Use Course Materials

To enable you to succeed in this course, these course materials employ


a learning model that is composed of the following components:

● Course map – Each module starts with an overview of the content


so you can see how the module fits into your overall course goal.

● Relevance – The relevance section for each module provides


scenarios or questions that introduce you to the information
contained in the module and provoke you to think about how the
module content relates to your interest in creating Java servlets.

● Overhead image – Reduced overhead images for the course are


included in the course materials to help you easily follow where
the instructor is at any point in time. Overheads do not appear on
every page.

About This Course xxvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
How to Use Course Materials

● Lecture – The instructor will present information specific to the


topic of the module. This information will help you learn the
knowledge and skills necessary to succeed with the exercises.

● Exercise – Lab exercises will give you the opportunity to practice


your skills and apply the concepts presented in the lecture. The
example code presented in the lecture should help you complete
the lab exercises.

● Check your progress – Module objectives are restated, sometimes


in question format, so that before moving on to the next module
you are sure that you can accomplish the objectives of the current
module.

● Think beyond – Thought-provoking questions are posed to help


you apply the content of the module or predict the content in the
next module.

xxviii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Icons and Typographical Conventions

The following icons and typographical conventions are used in this


course to represent various training elements and alternative learning
resources.

Icons
Additional resources – Indicates additional reference materials are
available.

Demonstration - Indicates a demonstration of the current topic is


recommended at this time.

Discussion – Indicates a small group or class discussion on the current


topic is recommended at this time.

Exercise objective – Indicates additional supportive topics, ideas, or


other optional information.

About This Course xxix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Icons and Typographical Conventions

Icons (Continued)

Note – Indicates additional important information.

Caution – Indicates a potential hazard to data or machinery.

Warning – Indicates anything that poses personal danger or


irreversible damage to data or the operating system.

xxx Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Icons and Typographical Conventions

Typographical Conventions
Courier is used for the names of commands, files, and directories, as
well as on-screen computer output. For example:

Use ls -al to list all files.


system% You have mail.

Courier bold is used for characters and numbers that you type. For
example:

system% su
Password:

Courier italic is used for variables and command-line


placeholders that are replaced with a real name or value. For example:

To delete a file, type rm filename.

Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:

Read Chapter 6 in User’s Guide.


These are called class options
You must be root to do this.

About This Course xxxi


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Notes to the Instructor

Philosophy
The Beyond CGI: Developing Java Servlets course has been created to
allow for interactions between the instructor and the student as well as
between the students themselves. In an effort to enable you to
accomplish the course objectives easily, and in the time frame given, a
series of tools have been developed and support materials created for
your discretionary use.

A consistent structure has been used throughout this course. This


structure is outlined in the “Course Goal” section. The suggested flow
for each module is:

1. Location of module in the course map


2. Context questions/module rationale
3. Module objectives
4. Lecture information with appropriate overheads
5. Lab exercises
6. Discussion: either as whole class or in small groups

To allow the instructor flexibility and give time for meaningful


discussions during the “relevance” periods, the lectures, and the
small-group discussions, a timing table is included in “General Timing
Recommendations.”

Course Tools
To enable you to follow this structure, the following supplementary
materials are provided with this course:

● Relevance

These questions or scenarios set the context of the module. It is


suggested that the instructor ask these questions and discuss the
answers. The answers are provided only in the instructor’s guide.

xxxii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Notes to the Instructor

Course Tools (Continued)


● Course map

The course map allows the students to get a visual picture of the
course. It also helps students know where they have been, where
they are, and where they are going. The course map is presented
initially in the “About This Course” section in the student’s guide.
The course map is then displayed at the beginning of each module
with the appropriate module highlighted.

● Lecture overheads

Overheads for the course are provided in two formats:

The paper-based format can be copied onto standard


transparencies and used on a standard overhead projector. These
overheads are also provided in the student’s guide.

The Web browser–based format is in HTML and can be projected


using a projection system that displays from a workstation. This
format gives the instructor the ability to allow the students to view
the overhead information on individual workstations. It also
allows better random access to the overheads.

● Small-group discussion

After the lab exercises, it is a good idea to debrief the students.


You can gather them back into the classroom and have them
discuss their discoveries, problems, and issues in programming
the solution to the problem in small groups of four or five, one-on-
one, or one-on-many.

About This Course xxxiii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Notes to the Instructor

Course Tools (Continued)


● General timing recommendations

Each module contains a “Relevance” section after the course map.


This section may present a scenario relating to the content
presented in the module, or it may present questions that
stimulate students to think about the content that will be
presented. Engage the students in relating experiences or posing
possible answers to the questions from the Relevance section

Spend no more that 10–15 minutes on this section.

Lecture Lab Total Time


Module
(Minutes) (Minutes) (Minutes)

Preface 30 No exercise 30

Module 1 75 45 120

Module 2 40 45 85

Module 3 35 45 80

Module 4 70 45 115

Module 5 60 45 105

Module 6 60 60 120

Module 7 15 30 45

Module 8 90 45 135

Module 9 30 30 60

Module 10 30 60 90

xxxiv Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Notes to the Instructor

Course Tools (Continued)


● Module self-check

Each module contains a checklist for students under “Check Your


Progress.” Give them a little time to read through this checklist
before going on to the next lecture. Ask students to see you for
items they do not feel comfortable checking off.

About This Course xxxv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Instructor Setup Notes

Purpose of This Guide


This guide provides all of the details that an instructor needs to know
both to initially set up the classroom environment and to prepare the
environment for each class offering.

Minimum Resource Requirements

Network

● Internal local-area network with server and clients (student


workstations).

● Network must support TCP/IP protocol.

● Workstations on the subnet must be able to access each other and


the server.

Hardware

● SPARCstation™ 4 systems or greater with 32 Mbyte RAM and 500


Mbyte internal disk

● Computer projection system for displaying HTML slides

Software

● Solaris™ 2.5 or greater

● Netscape Navigator™ 4.0.3 or greater (4.04 with patch)

● The Java Development Kit (JDK™) 1.1.6 or greater with


documentation

● The Java Web Server version 1.1.1 for Solaris (with SSL and
JavaServer Pages)

xxxvi Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Instructor Setup Notes

Minimum Resource Requirements (Continued)

Software

● A database compatible with JDBC™ (mini SQL: mSQL).

● The Imaginary database driver classes for use with the Java
programming language.

● SL-310 lab files (these contain a copy of Java Web Server 1.1.1, JDK
1.1.6, mSQL, and Imaginary drivers). The operating system and
browser must be acquired separately.

Assumptions About the Lab


The following assumptions are made about the lab used for this
course:

● There is one workstation per student in the lab.

● Students work at the same machine throughout the course.

● An additional workstation is available for the instructor. The


instructor’s machine will be used to run the database software.
This machine is referred to as the database server and may be a
different machine than the server where user accounts, JDK, and
browser mount points are established.

About This Course xxxvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Setting up for an SL310 Class

The following procedures must be completed before each SL-310 class:

Student Workstations
Install the following software on each of the student workstations:

● Solaris operating system.

● Java Web Server 1.1.1 (with SSLand JavaServer Pages). An archive


file containing the Java Web Server is located within
SL310_LF/Home.

● Lab Files. The lab files are located within SL310_LF/Home.

Server Machine
● Solaris or Windows NT operating system

● Netscape 4.0.3 or greater (4.04 with patch)

● Java Development Kit 1.1.6 or greater

● mSQL database software

Projection System and Workstation


If you have a projection system for projecting HTML slides and are
planning to use the HTML slides, you need to do the following:

● Install the HTML overheads on the workstation connected to the


projection system so you can display them with a browser during
lecture.

To install the HTML overheads on the machine connected to your


overhead projection system, copy the HTML and images
subdirectories provided in the SL310_OH directory to any directory
on the overhead workstation machine. These files use
approximately 2 Mbytes of disk space.

xxxviii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Setting up for an SL310 Class

Projection System and Workstation (Continued)


Display the overheads in the browser by choosing Open ➤ File
and typing the following in the Selection field of the pop-up
window:

/location_of_HTML_directory/OH.Title.doc.html

● Set up an overhead-projection system that can project instructor


workstation screens.

Note – This document does not describe the steps necessary to set up
an overhead projection system because it is unknown what will be
available in each training center. This setup is the responsibility of
each training center.

About This Course xxxix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Files

All of the course files for this course are available from the Enterprise
Services Web server, at this site:
http://education.central/courses/Released.html. You must
know the user ID and password; see your manager for these if you
have not done this before.

The SL310 course consists of the following components:

● Instructor guide

The SL310_IG directory contains the FrameMaker files for the


instructor guide (student guide with instructor notes). The ART
directory is required for printing this guide.

A PostScript directory includes the instructor guide in PostScript™


format.

● Student guide

The SL310_SG directory contains the FrameMaker files for the


student guide. The ART directory is required for printing this
guide.

The PS directory includes PostScript files of the IG, SG, and Frame
OH.

● Art

The SL310_ART directory contains the supporting images and


artwork for the student and instructor guides. This directory is
needed in order to print the student and instructor guides and
should be located in the same directory as SL310_IG and
SL310_SG.

xl Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Course Files

● Overheads

The SL310_OH directory contains the instructor overheads. There


are both HTML and FrameMaker versions of the overheads.

● Lab files

The SL310_LF/Home directory contains the following files and


subdirectories which are to be installed on each client workstation:

▼ modx-modulename– Ten directories containing the lab files and


solutions to be used in the exercises for this course, as well as
the examples used in the student guide. Each module directory
should be copied to the home directory for each student
account on each workstation.

▼ Java Web Server 1.1.1 archive (for example, jws1.1.1.tar.Z.)

Note – You will need approximately 2.5 Mbytes of disk space for the
lab files and approximately 25 Mbytes of disk space for Java Web
Server.

The SL310_LF/solserver directory must be installed on the Solaris


server and made available to each client workstation:

● JDK 1.1.6 documentation

● JDK 1.1.6.

About This Course xli


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Note – The “for example” items in this section refer to directories,


accounts, and file names used during the setup of this course.

Student Workstations

Recommended Partitions and Sizes

Each machine should have 500–600 Mbytes of disk space.

Note – If you do not have a server machine, each student workstation


will require a 1-Gbyte disk for installing the JavaWeb Server, JDK, JDK
docs directory, database, and browser. The database should reside on
the instructor’s workstation.

Student Accounts

Install one account on each workstation (for example, user student


with no password), and require students to use the same workstation
throughout the course. A home directory for each account may be put
on a server and made available on each machine. Or, create an
/export/home/student directory on each machine.

Note – Follow the procedures used at your training center for creating
student accounts on each workstation.

xlii Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Student Workstations

Lab Files in Each Account

After you have created the student accounts, copy the contents of the
SL310_LF/Home directory to the home directory for each student
workstation (approximately 2.5 Mbytes).

Mounting Server Directories

If a server is present, mount the directories from the server that


contain the JDK, JDK docs, and browsers.

Environment Variables

For each student account, set the following environment variables in


the appropriate startup file for the student workstation(.cshrc for C
shell, .profile for K shell):

● Set JAVA_HOME to the local installation directory or mount point


for the JDK software (example:
c:\jdk1.1.6/net/server/opt/jdk1.1.6).

● Set JSERV_HOME to server_root to where the Java Web Server


is installed on each client machine (for example,
/opt/JavaWebServer).

● Set the PATH variable to include $JAVA_HOME/bin (for accessing


the compiler for the Java programming language)and the local
absolute directory or mount point for the brower’s executable.

● Set the CLASSPATH variable to include


$JSERV_HOME/lib/jsdk.jar,$JSERV_HOME/lib/x509v1.jar,
$HOME/mod4-jdbc/imaginary, $JSERV_HOME/classes (for the
com.sun.server classes), and . (for the current directory).

About This Course xliii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Student Workstations

Java Web Server Installation

Copy the archive file, found within SL310_LF/Home, to each student


workstation (for example, /opt/). Change to the directory where you
copied the archive file and install Java Web Server as per the
instructions in Appendix B, “Using Java Web Server.” This document
is found in the SL310_IG directory.

Invoke Java Web Server, on each student machine, according to the


instructions in Appendix B, “Using Java Web Server.” This document
is found in the SL310_IG directory.

Generating a UDP Broadcast Address

Module 7 requires a UDP broadcast address to be used by the entire


classroom. To create a UDP broadcast address:

1. Determine the subnet mask for the classroom network (ifconfig


-a); for example, 255.255.255.0

2. Determine an IP address for one of the classroom’s machines


(ifconfig -a); for example, 129.152.57.255

3. Invert the subnet mask; for example, 255.255.255.0 becomes


0.0.0.255.

4. OR (Conditional OR) the subnet mask with the IP address; for


example, 129.152.57.255 || 0.0.0.255 becomes
129.152.57.255

Register this address in each naming services file, such as a hosts file,
on each student workstation. An entry in the hosts file looks like:

129.152.57.255 localbroadcast

or

255.255.255.255 thewholeworld

xliv Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Student Workstations

Generating a UDP Broadcast Address (Continued)

It might be hard to add a broadcast address to the hosts file of NIS or


NIS+ on an ad hoc basis. In such conditions:

1. Edit /etc/hosts and add the broadcast entry

2. Edit the /etc/nsswitch.conf file and locate the line


identifying the naming service. This will look similar to:

hosts: nis [NOTFOUND=return] files

3. Modify the naming services line by moving the files keyword


directly after the nis keyword. For example:

hosts: nis files [NOTFOUND=return]

Note – This procedure is unnecessary in JDK 1.2, as an address may be


used without adding it to naming services.

Refer to Appendix D, “Java Socket Programming,” for additional


information on determining subnet masks.

About This Course xlv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Server Machine (if Applicable)


After installing the Solaris 2.4 or later operating environment, install
the following software in directories that are exported to and mounted
by student workstations.

Java Development Kit and docs Directory

Acquire and install the latest Java Development Kit (JDK™) and JDK
doc files from
http://java.sun.com:80/products/jdk/1.1/index.html using
the provided installation instructions. The JDK for Sun Solaris, used
during the creation of this course, are located in
SL310_LF/solserver.

Note – Together, the JDK and JDK docs directory use approximately
34 Mbytes of disk space.

Browsers

Download the Netscape browser 4.03 or higher (for example, Netscape


Navigator 4.04 with patch) from http://www.netscape.com. Use the
provided installation instructions to install it on each student
workstation or via a mount point from the server.

xlvi Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Configuring the Classroom

Server Machine (if Applicable)

MiniSQL Database

Designate one of the student workstation as an instructor workstation.


Select a location on the instructor workstation for the mSQL database
directory (for example, /opt/). Copy the SL310_LF/Hughes directory
to this directory. Configure the /Hughes/msql.conf file to contain the
following settings:
port = 1114
user = username
admin user = root
Change directory to Hughes/bin/ and execute the mSQL database
daemon, ./msql2d -f ../msql.conf

You must specify the name of the configuration file you are using
when using each of the mSQL utilities.

About This Course xlvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
xlviii Beyond CGI: Developing Java Servlets
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Servlet Basics 1

Course Map
This module provides an introduction to servlet development by
examining and comparing a simple HelloWorld CGI script and servlet.

Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

1-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following question is relevant in understanding the


topics presented in this module:

CGI scripts are commonly used to add functionality to Web pages.


What benefits do servlets offer over CGI?

✓ Requests processed by servlets are processed faster than by equivalent CGI’s because
servlets need to be loaded only once. CGI programs are loaded for each client request.
Servlets are reloaded (automatically) only if they change. FastCGI attempted to fix this
problem.

✓ Servlets can handle multiple requests concurrently (they are multithreaded).

✓ Servlets are implemented with Java technology, a robust object-oriented language.


Servlets can take advantage of any technology available to the Java platform such as RMI.

✓ Servlets can be preloaded by a Web server upon startup.

✓ Determine how many people in your class are familiar with CGI.

1-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Objectives

Upon completion of this module, you should be able to

● List the steps involved in the CGI request and response


mechanism

● Identify the importance of a content type in a response

● Describe, in one sentence, the term servlet

● Define three or more uses for servlets

● List the steps involved in the servlet request and response


mechanism

● Identify the class used to create an HTTP servlet

● Create and invoke a basic servlet

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Java Servlet Tutorial. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/
servlet_tutorial.html.

● Developing Java Servlets. Crawford, William. [Online]. Available:


http://webreview.com/97/10/10/feature/index.html.

● HTML Web Publisher’s Construction Kit. Fox, David, and Troy


Downing. 1995. Waite Group Press.

Servlet Basics 1-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Common Gateway Interface (CGI)

Overview
The common gateway interface (CGI) greatly increased the usefulness
of the Web. CGI provides a mechanism that allows a Web client to
execute programs on the server. These programs, called CGI scripts,
can be written in popular languages such as C, C++, Visual Basic, and
Perl.

Example Uses
A CGI script might perform a simple task such as returning the
current date from a server. Or, more commonly, a CGI script could be
used to parse data in a hypertext markup language (HTML) form and
return a result to the browser, based on the data parsed. Other uses of
CGI scripts are:

● Providing an entry point into a Web server utility such as the


UNIX® finger utility.

1-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Common Gateway Interface (CGI)

Example Uses (Continued)


● Returning database information based upon a query from a Web
browser.

● Performing a computation, such as the total for items ordered


from an on-line catalog, and returning the result to a Web browser.
✓ CGI enhanced the Web by providing a more advanced mechanism for client interactions.
CGI scripts can provide database access, server information, or shopping services. The
processing of a CGI script is done on the server instead of a client. This server-side
processing can provide better real-time interactions.

Servlet Basics 1-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
CGI Request and Response

CGI scripts are request/response oriented. This means that scripts are
invoked based on some sort of request and, usually, return some sort
of response to the requestor. Figure 1-1 provides an overview of the
request/response nature of CGI scripts.

Gateway
programs 2

2 Shell 3
1
HTTP request Run
CGI
CGI script
5
HTTP response Output 4

Browser
(WWW client)
HTTP (Web)
server

Figure 1-1 CGI Request and Response Overview

Request and Response Mechanism


The request/response mechanism for a CGI script works as follows:

1. A client Web browser makes a request, containing an HTTP


header and message body, to a CGI program.

2. The HTTP server parses the request information and starts a new
shell process. The request is stored either in a series of CGI
environment variables or through standard input.

3. The server then runs the script, which may run one or more
scripts, and then, optionally, generate an output consisting of a
HTTP header and message body.

4. The output is forwarded to the HTTP server.

1-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

CGI Request and Response

Request and Response Mechanism (Continued)


5. The HTTP server forwards the output to the client Web browser.
✓ Other request/response protocols are HTTPS and FTP.

CGI and HTTP


CGI scripts are written to handle requests and responses over the
HTTP. HTTP is the request/response protocol used by Web servers to
communicate with Web browsers on the Internet. A client makes a
request for data to a server and the server responds with the response
or data. An HTTP response must contain a header that tells the Web
server the type of data the response contains. As a developer of a CGI
script, you will know the type of data the CGI script will receive.
✓ HTTP is the network protocol used by Web servers and clients for interaction. HTTP
contains a header used to describe the data’s content.

Servlet Basics 1-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
An Example HelloWorld CGI Script

Script Code
Shown here is a helloworld.pl CGI script that is invoked by a Web
browser and returns a string. The .pl extension identifies the script as
a Perl script. There are two main functions of the form processing CGI
script: setting content type and returning a response.
1 #!/usr/local/lib/perl4/bin/perl
2 # Perl 4.0
3
4 # Print out a content-type for HTTP/1.0 compatibility
5 print "Content-type: text/html\n\n";
6
7 &print_results;
8
9 sub print_results
10 {
11 print "<HTML><HEAD><TITLE>Hello World</TITLE>
</HEAD><BODY><h1>Hello World</h1></BODY></HTML>";
12 }
✓ This simple CGI script that is used to display “Hello World” in a Web browser. This course
is not intended to teach students Perl, and, therefore, does not provide a full description
of Perl syntax.

1-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Common Gateway Interface Script

Setting Content Type


The first thing that this CGI script does is specify a header type of
Content-Type:text/html for the response (line 5). Content type is
used to specify the Multipurpose Internet Mail Extension (MIME) data
type for a response. MIME is a coding scheme used to differentiate
various types of data. Web browsers and Web servers often support
several different MIME types. You must specify the MIME type and
sub-type when using the content type header. In the example, text is
the MIME data type, and html is the sub-type (the type of text
requested or returned). Appendix A, “CGI, HTTP, and Servlets,” lists
all of the MIME types available.

Servlet Basics 1-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld CGI Script

Returning a Response
Once the text/html response type is defined, the script composes a
the body of the response using the Perl print command to print to
standard output (line 11). The HTML generated by a script is often
referred to as dynamic HTML. This term is used because the HTML is
dynamically created based on a request to a script.

1-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld CGI Script

Invoking the Example CGI Script


CGI scripts are commonly placed in the server_root/cgi-bin/
directory. You can invoke your CGI script with a Web browser once
you have placed your CGI script in this directory. You can type the
following in your uniform resource locator (URL) field to invoke the
helloworld.pl script from your Web browser:
http://host_name:port/cgi-bin/helloworld.pl

Note – The mod1-basic/examples/ directory contains a copy of the


helloworld.pl script.

Servlet Basics 1-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Web Server and Common Gateway Interface Support

Most Web servers support CGI scripts. In addition, a Web server will
also support one or more CGI scripting languages. Popular languages
are Perl, C, and tool command language (TCL).

1-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

What Is a Servlet?

Definition
Servlets are modules that run inside request/response-oriented
services, extending these services in some manner. Services are bodies
of code that implement an application-level protocol such as file
transfer protocol (FTP), dynamic host configuration protocol (DHCP),
or HTTP.
✓ Another way of describing the service/servlet relationship is: services load and run
servlets, which then accept zero or more requests from clients and return data to clients.

✓ Servlets differ from CGI here in that servlets are geared toward additional services, not
just an HTTP server.

Servlets are written in the Java programming language, which enables


them to access the benefits that the language provides.
✓ Programmers of Java programming language may have started their Java development
with applets. Servlets are essentially “faceless” applets that enhance the functionality of
a Web server.

Servlet Basics 1-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
What Is a Servlet?

Example Uses
✓ Servlets do not have to be HTTP service related. For example, someone might create a
FTP service which supported servlets. Services might also be thought of as system-level
processes that implement application-level protocols.

Like CGI scripts, servlets are capable of performing tasks such as


returning a server’s date or parsing form data. Additional uses for
servlets include:

● Allowing access to remote objects developed using the Java


programming language through the use of Java technology RMI or
Java IDL technology

● Tracking large amounts of information across several Web pages,


such as items purchased in an on-line catalog

● Allowing collaboration among multiple users logged into the same


Web server (such as a chat servlet)
✓ Survey students to find out the types of servlets that they want to develop and deploy.
Ask them what current CGI solutions they deploy on their server. This will give you an
idea of the types of servlet topics your audience is interested in.

✓ Have students open their browser to the Java Web Server documentation web site,
file:server_root/doc/apidoc/packages.html.

1-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Servlet Request and Response

Request and Response Overview


HTTP servlets receive a request, in the form of an
HttpServletRequest object and return a response in the form of an
HttpServletResponse. As with CGI, servlets are also
request/response oriented.

Figure 1-2 provides an overview of the request/response nature of a


servlet scripts.

Class 2
loader Invoker
Is servlet No
loaded? 2
1 Yes 3
HTTP request

5 service
HTTP response Output 4 thread
Browser
(WWW client)
HTTP (Web)
server

Figure 1-2 Servlet Request and Response Overview

✓ Mention that HTTP servlet extends GenericServlet which is an implementation of the


Servlet interface.

✓ These objects/packages are covered in javax.servlet and javax.servlet.http. Show


students this documentation.

The request/response mechanism for an HTTP servlet works as


follows:

1. A client Web browser sends a request, containing an HTTP


header and message body, to a servlet.

Servlet Basics 1-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Servlet Request and Response

Request and Response Overview (Continued)


2. The HTTP service receives the request, loads the servlet if it isn’t
already loaded, and launches the invoker servlet.
✓ The service actually calls the servlet’s init method when the servlet is initially loaded.
The init method is further discussed in Module 2.

3. The invoker then calls the servlet’s service method which runs
within its own thread. The servlet can run one or more servlets,
and then generates an output. The Web server spawns a new
thread for subsequent calls to the servlet’s service routine.

4. The output is forwarded back to the HTTP service.

5. The HTTP service forwards the output to the client Web browser.

1-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Servlet Request and Response

HTTP and Servlets


The majority of servlets are developed for the HTTP protocol as an
alternative to CGI-based solutions. The API for Java technology
servlets (“Java servlets”) provides a subclass of the GenericServlet
abstract class, called HttpServlet, for use in developing HTTP-based
servlets.
✓ Java servlet interfaces and classes are as follows:

• javax.servlet – interface

• javax.servlet.GenericServlet – abstract class

• javax.servlet.http.HttpServlet – sub-class of GenericServlet

✓ The GenericServlet class is the superclass for a servlet which may not rely on HTTP.
HttpServlet is a class which is extended to create HTTP-centric servlet. Developers use
GenericServlet if they need to provide more details than HttpServlet provides.

Servlet Basics 1-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

The following is the source code for a HelloWorld Java servlet. The
HTTP protocol generates an HTTP request, using the GET method,
which is sent to the Web server when the servlet is invoked from the
browser. The servlet is a .java file that has been compiled into a
.class file and stored on the Web server.

1-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
An Example HelloWorld Servlet

Servlet Code
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4
5 public class HelloWorld extends HttpServlet{
6
7 public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
8
9 res.setContentType("text/html");
10
11 try{
12 PrintWriter out = res.getWriter();
13 out.println("<HTML>");
14 out.println("<HEAD><TITLE>Hello World
</TITLE></HEAD>");
15 out.println("<BODY>");
16 out.println("<h1>Hello World</h1>");
17 out.println("</BODY></HTML>");
18 out.close();
19 } catch(IOException ioe) {
20 getServletContext().log (ioe,"Error in HelloWorld");
21 }
22 }
23 }

The first thing that this servlet code does is specify the appropriate
import libraries: java.io, javax.servlet and javax.servlet.http.

Servlet Basics 1-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

HttpServlet
The import statements are followed by the class declaration (line 5).
Notice that the class extends HttpServlet. This is a specific
implementation of the javax.servlet.GenericServlet abstract
class. You need only subclass an HttpServlet to develop an HTTP-
specific servlet. Remember, you can create servlets to support services
other than HTTP.

1-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

The service Method


The doGet method is one of several “service” methods supported by
the HttpServlet. A servlet’s service method is invoked for each
request to a servlet. A servlet must override one of HttpServlet’s
service methods to receive requests.

The example servlet overrides doGet because the HTTP protocol


generates a GET, by default, when a CGI script or servlet is invoked
directly from a URL (line 7). HTTP methods are further discussed in
Module 2. All HttpServlet service methods accept an HttpRequest
and HttpResponse object.
✓ Service methods may be referred to as “helper” methods for specific HTTP request types.

Servlet Basics 1-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

Setting Content Type


The servlet uses the HttpServletResponse object, provided to the
servlet’s service method when the servlet is called, to generate a
response (line 12). The HttpServletResponse object provides several
methods for manipulating the header and body of a response.

As with a CGI script, the servlet sets the content type within the
responses header (line 9). The content type is set using
HTTPServletResponse’s response.setContentType method. You
can also use setContentLength to set the length of the response.
✓ The header data defaults are text/plain.

✓ Setting length affects browser progress bars.

1-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
An Example HelloWorld Servlet

Setting Content Type (Continued)


HttpServletResponse also provides the setHeader and
setIntHeader methods for adding fields to an HTTP response’s
header (line 9).

Note – The mod1-basic/examples directory contains a copy of


request for comments (RFC) 2068. This RFC describes the HTTP 1.1
protocol (headers and body).

Servlet Basics 1-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

Returning a Response
HttpServletResponse provides both PrintWriter and
ServletOutputStream for returning the body of a response to a
client. The way you choose to have your servlet respond depends on
the type of data your servlet will return:

● Use response.getWriter to return a PrintWriter used for text


data (localized).

● Use response.getOuputStream to return a


ServletOutputStream used for binary data.

The PrintWriter and OutputStream provide options to print the


response. The example uses PrintWriter.println to create the
necessary dynamic HTML (lines 12–18). The PrintWriter is closed
using out.close (line 18).

1-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

An Example HelloWorld Servlet

Writing Exceptions to Log Files


A service runs within an environment, or context. Servlets running
within the same service share the same servlet context. Servlet contexts
are implemented by service developers for a Web server.

The javax.servlet.servletContext interface offers two useful log


methods. The first accepts an exception and a string and prints them to
server_root/logs/javawebserver/event_log. The second log
method also prints to
server_root/logs/javawebserver/event_log, but simply accepts
a string. These log methods are useful for debugging your servlets.

Note – HttpServlet provides a standard log method that you can use
to log information to
server_root/logs/javawebserver/event_log. This log method
calls the servletContext log method.

Servlet Basics 1-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Invoking the Example Servlet

Invocation URL
Servlets are commonly placed in the /servlets/ directory under the
server_root directory for Java Web Server. Servlets placed in this
directory can be invoked directly using their class names. For example,
if HelloWorld.class were placed in the server_root/servlets
directory, the syntax to invoke the servlet would be as follows:
http://host_name:port/servlet/servlet_class

For example:
http://fuggles:8080/servlet/HelloWorld
✓ The /servlets directory should primarily be used to test and debug the servlets you
create. This is because servlets in this directory will not have access items such as native
methods and static variables. The module covering servlet security will further discuss
this topic.

✓ Do not put the .class extension on servlet_class.

1-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Invoking the Example Servlet

servlet/ Versus servlets/


Notice that you place servlets in the server_root/servlets
directory, but launch servlets from servlet/. Java Web Server uses a
special server-side mechanism called servlet aliasing to call another
servlet, the invoker servlet, which is used to invoke your servlet’s
service routine each time it is called.

Servlet aliases are pathname mapping rules that the Java Web Server
uses to invoke servlets. These rules enable you to use a shortcut URL
to call a servlet from your browser, embed a shortcut into your files, or
perform a URL redirect such as invoking the invoker servlet when the
servlet/ reference is used. Servlet aliases are further discussed in
Module 3. Appendix B, “Using Java Web Server,” contains instructions
covering the use of servlet aliases with Java Web Server.

Note – The mod1-basic/examples/ directory contains a copy of the


HelloWorld servlet source and .class file.

Servlet Basics 1-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Web Server Servlet Support

Servlets require a special servlet environment, or servlet engine, to run.


Servlet support is built in to several popular Web servers including the
Java Web Server available from Sun Microsystems™. This course uses
the Java Web Server to invoke the servlets you will create in each
exercise.
✓ This course focuses on the use of servlets with the Java Web Server. Students can
contact other Web server manufacturers for information about the use of servlets with
their Web server products.

✓ It is important to tell students that the focus of this course is on the use of the Java
servlet API. The majority of the exercises in this course should work on a Web server if
the Web server supports the Java server API.

✓ The Java Web Server is actually a by-product of the Java Server Toolkit, a toolkit used for
developing Web server services. The Java Server Toolkit is available in source form, as
the Java Server Toolkit, and in binary form, as the JavaServer Engine.

1-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1

Review of Servlet Basics

The basics of HTTP servlet development consist of developing a


servlet that receives a simple HTTP GET request and, optionally,
returns a response to a Web browser. This is accomplished through:

● Subclassing the HttpServlet class by extending HttpServlet.

● Overriding one of HttpServlet’s service methods to accept servlet


requests. The example servlet uses doGet because the HTTP
protocol generates a GET when a CGI script or servlet is invoked
directly from a URL.

● Setting the content type and, optionally, the length of the response
using setContentType and setContentLength, respectively.

● Using response.getPrintWriter, for text data, or


response.getServletOutputStream, for binary data, to submit a
response.

● Using the PrintWriter or ServletOutputStream’s println


method to generate dynamic HTML.

Servlet Basics 1-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Review of Servlet Basics

● Closing the PrintWriter or ServletOutputStream using


output.close.

● Using getServletContext.log to print exceptions and messages


to the event_log.

1-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Exercise: Developing a Simple HTTP Servlet

Exercise objective – Create, configure, and invoke a basic HTTP


servlet that responds to the GET methods of the HTTP protocol. Create
a servlet that writes to the event_log.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.
✓ Most of the modules in this course contain two exercises. One exercise is a simple, step-
by-step exercise that reinforces what is learned within the module. The second exercise
contains minimal instructions and are intended for advanced programmers of Java
language. Advanced students are encouraged to try the second exercise in each module
(if applicable).

✓ Remember: This course uses Java Web Server to execute the servlets created in the
exercises. Go over Appendix B with students and point out sections such as “Running
Java Web Server,” “Displaying the Default Home Page,” and “Launching the
Administration Applet.” Guide students through the configuration of their first servlet.

Servlet Basics 1-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Exercise: Developing a Simple HTTP Servlet

Tasks

Creating BasicServlet.java

1. From your home directory, change directory to mod1-


basic/lab/.

2. Open the BasicServlet.java file in an editor.

3. The BasicServlet.java file contains several comments


indicating where you must insert code. Insert code within
BasicServlet.java to do the following:

Handle HTTP protocol GET methods by overriding the doGet


service method.

▼ Set the response header field and content type.

▼ Get a writer or output stream from HttpServletResponse,


depending on type of return data returned by the servlet.

▼ With the writer or output stream, print out a response


(supplied).

▼ Close the writer or output stream.

4. Save the BasicServlet.java file after you have made changes.

5. Generate a BasicServlet.class file.

% javac BasicServlet.java

6. Copy BasicServlet.class to the server_root/servlets


directory.

1-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Exercise: Developing a Simple HTTP Servlet

Tasks

Configuring and Invoking BasicServlet.java

1. Add BasicServlet to Java Web Server. Refer to Appendix B,


“Using Java Web Server,” for more information.

2. Close the Java Web Server – Web Service window once


BasicServlet has been added.

3. Invoke BasicServlet by typing the following URL in your Web


browser:
http://host_name:8080/servlet/BasicServlet

You should see BasicServlet HTML text appear. This URL


invokes BasicServlet directly; it points to the servlet using a URL
from within a Web browser.

Servlet Basics 1-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Exercise: Developing a Simple HTTP Servlet

Tasks

Create a Servlet That Writes to the event_log

Use the servlet API’s log methods to create a servlet that writes to the
server_root/logs/javawebserver/webpageservice/event_log.
The servlet should obtain and write the client’s IP address and date.
The servlet should also notify the client when the log file has been
written to and display the entry on the client’s browser.

1-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Exercise: Developing a Simple HTTP Servlet

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

Servlet Basics 1-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ List the steps involved in the CGI request and response


mechanism

❑ Identify the importance of a content type in a response

❑ Describe, in one sentence, the term servlet

❑ Define three or more uses for servlets

❑ List the steps involved in the servlet request and response


mechanism

❑ Identify the class used to create an HTTP servlet

❑ Create and invoke a basic servlet

1-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
1
Think Beyond

This module primarily discussed handling servlet responses. What


might you do as part of handling a request to a servlet?

Servlet Basics 1-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Forms Processing With Servlets 2

Course Map
This module builds upon basic servlet development through the
introduction of HTTP request handling and the creation of a form-
processing servlet.
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

2-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


the topics presented in this module.

Forms and servlets provide a mechanism for a Web client to submit


information to a Web server. Forms consist of any number of fields,
check boxes, buttons, and menu items. What are some examples of
forms you might create or use?
✓ A few examples are customer profile forms, credit card information forms, and database
query forms.

What must a CGI script do to parse an HTTP request?


✓ Read the request from standard input. Parse the request using the libraries made available
by your scripting language.

2-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Objectives

Upon completion of this module, you should be able to

● List the two parts of a form-processing solution

● Identify the two primary tags used for building HTML forms

● List the three attributes used in the <FORM> tag

● Explain the seven HTTP method types

● Identify how to invoke a CGI script or servlet from an HTML form

● List the seven HttpServlet service methods

● Explain the differences among getParameterNames,


getParameterValues, getParameter, getQueryString,
parseQueryString, getPrintWriter, and
getServletOutputStream servlet APIs

● Identify the use of the getServletInfo method

● Write a form-processing servlet

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Java Servlet Tutorial. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/
servlet_tutorial.html.

● Replacing CGI Scripts with Servlets. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/cgi_forms.html.

Forms Processing With Servlets 2-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

A Basic Form Solution

Two items required to complete a basic form solution are

● The HTML form

● A CGI script or servlet used to process the form data

Examples of each items are shown and explained in the following


sections.

2-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example HTML Form

HTML forms usually contain a combination of fields, buttons, check


boxes, and a button used to submit the form data to a Web server.
Most HTML books discuss the HTML tags required to create a form.
Figure 2-1 shows a simple HTML form.

Figure 2-1 A Simple HTML Form

Forms Processing With Servlets 2-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example HTML Form

The HTML source code for the form in Figure 2-1 is as follows:
1 <HTML>
2 <HEAD>
3 <TITLE>Test Form</TITLE>
4 <BODY>
5 <FORM METHOD="POST" ACTION="/cgi-bin/form.pl">
6 <h1>Please fill out the following form data</h1>
7 First Name:<INPUT TYPE="TEXT" NAME="FNAME">
8 <p>
9 Last Name:<INPUT TYPE="TEXT" NAME="LNAME">
10 <p>
11 Position:
12 <SELECT NAME="SELECT">
13 <OPTION>Software Engineer
14 <OPTION>Editor
15 <OPTION>Course Developer
16 <OPTION>Instructor
17 </SELECT>
18 <p>
19 I would like to receive marketing materials
20 <INPUT TYPE="CHECKBOX" NAME="CHECKBOX">
21 <p>
22 <INPUT TYPE="SUBMIT">
23 <INPUT TYPE="RESET">
24 </FORM>
25 </BODY>
26 </HTML>

2-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example HTML Form

The <FORM> Tag


An HTML form is declared using the <FORM> tag. The <FORM> tag
takes three parameters. These are:

● METHOD

● ACTION

● ENCTYPE

Forms Processing With Servlets 2-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example HTML Form

The <FORM> Tag

METHOD

The METHOD attribute identifies how the data will be sent from the
browser to the Web server. There are several HTTP method types, each
with its own characteristics. Table 2-1 lists the HTTP methods
supported by HTTP 1.1 protocol.

2-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example HTML Form

The <FORM> Tag

METHOD (Continued)

Table 2-1 HTTP Methods Supported by HTTP 1.1 Protocol.

HTTP Method Description

GET The body of the message is appended


to the URL, separated by a question
mark. Generally used for small
queries.
HEAD Similar to GET, but the server doesn’t
return a message body in the
response.
POST The body of the message is sent as a
stream of data. Generally used for
forms.
PUT Requests that the server store the
resource specified in the request URL.
DELETE Specifies that the server delete the
resource identified in the URL.
TRACE Performs a loopback of the request
message.
OPTIONS Requests the options available
between the browser and the Web
server specified in the URL.

Forms Processing With Servlets 2-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example HTML Form

The <FORM> Tag

METHOD (Continued)

Module 1 mentioned that an HTTP GET is generated when a CGI script


or servlet is invoked as part of a URL. This is because the default
METHOD for any request is a GET. Information received through a GET
request is stored, by the Web server, in an environment variable called
a query string. The GET method is used primarily for small queries or
requests.

POST is usually more reliable than GET and allows more data to be sent
to the Web browser. Therefore, POSTs are recommended for HTML
form requests.

The HEAD method is used for sending header information only, usually
to test hypertext links, and is deemed inadequate for most requests.
✓ The HttpServlet class or its API will display a doXXX for each of the HTTP method types.

The PUT and DELETE methods are used to modify information on a


Web server. These HTTP methods are not often used because of
security reasons.

Finally, TRACE and OPTIONS are useful when determining the


capabilities between a Web browser and a Web server.

Note – The mod2-forms/examples directory contains a copy of RFC


2068. This RFC describes the HTTP 1.1 protocol.

✓ Only GET and POST will be worked with in this course. You should be able to implement
other HTTP service methods if you understand how to use GET and POST.

2-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example HTML Form

The <FORM> Tag

ACTION and ENCTYPE

The ACTION attribute specifies the destination for the form


information. In most cases this is a CGI script or servlet. The script or
servlet defined by ACTION may be relative to the server_root or an
absolute uniform resource locator (URL). This attribute is optional. If
omitted, ACTION defaults to the current Web page’s URL.

The ENCTYPE attribute is used to encode the data. This attribute can be
used only if your METHOD is a POST. In most cases, you do not need to
use this attribute.

Forms Processing With Servlets 2-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example HTML Form

The <INPUT> Tag


The INPUT tag is used to identify the individual input fields in a form.
You should also use the INPUT tag to identify a button used to submit
the form data once the form has been filled out. After the end-user
clicks on the Submit button, the form is sent as a data stream (for a
POST) to the servlet specified in the <FORM> tag at the top of the HTML
file.

2-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Script

The following Form.pl CGI script is invoked by the example HTML


form and returns the form data to the browser. There are four main
functions of the form processing CGI script: setting content type,
reading the request, parsing the request, and returning a response.

Forms Processing With Servlets 2-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Script

Script Code
1 #!/usr/dist/pkgs/perl/bin/perl
2
3 # Print out a content-type for HTTP/1.0 compatibility
4 print "Content-type: text/html\n\n";
5
6 &parse_data;
7
8 &print_results;
9
10 sub parse_data
11 {
12 read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
13
14 # Split the name-value pairs
15 @pairs = split(/&/, $buffer);
16 }
17
18 sub print_results
19 {
20 print "<HTML><HEAD><TITLE>Form Object
21 List</TITLE></HEAD><BODY>";
22 print "Object/Value pairs passed in by form:<BR><BR>";
23 foreach $pair (@pairs) {
24 ($name, $value) = split(/=/, $pair);
25
26 # Remove plus signs and percent (%) encoding
27 $value =~ tr/+/ /;
28 $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
29 print "$name: $value<BR>";
30 }
31 }

The lines in bold represent the bulk of the work done by the example
form-processing script. These lines are explained in the following
sections.

2-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Script

Setting Content Type


The first thing that the example CGI script does is specify the header
type for the response (line 4).

Reading the Request


The script reads the entire body of the request, from standard input,
after setting content type (line 12).

The Perl read command accepts a handle to standard input (STDIN), a


new buffer to hold the message ($buffer), and a CGI environment
variable holding the message body’s length ($ENV).

Forms Processing With Servlets 2-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Script

Parsing the Request


The buffer, now containing the message body, is parsed to create
name=value pairs corresponding to the fields and their values in the
HTML form (line 15).

Prior to parsing, the buffer contains a stream of data: name=value pairs


delimited by the “&” character. For example:
LNAME=Richards&NAME=ani.richards@sun.com&CHECKBOX=on&
SELECT=OPTION+1

The Perl split command accepts a delimiter (&) and the buffer
containing the unparsed data ($buffer). The split command parses
each name=value pair into its only place within an array (@pairs).

2-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Script

Parsing the Request (Continued)


Certain form items, such as a SELECT box, can produce multiple values,
each referred to by the same name. For example:

HARDWARE=CPU&HARDWARE=Sparc&HARDWARE=21Display

A CGI script must do some extra work, namely ensuring what values
belong to what names, to parse this type of data.
✓ These items use the MULTIPLE keyword.

Forms Processing With Servlets 2-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Script

Returning a Response
The data is further parsed and returned to be displayed by the Web
browser (lines 23, 24, and 29).

The script iterates through each item in the array, parses out the equals
sign (=) for each name=value pair, and then prints the result (each pair)
to standard output as:
name: value

2-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

Invoking the Example Form-Processing Script

HTML files are commonly placed in the


server_root/public_html/ directory. You can invoke your CGI
script with a Web browser once you have placed your HTML page in
this directory, and placed your CGI script in the server_root/cgi-
bin/ directory. You can type the following in your URL locator to
invoke the form.html page from your Web browser:
http://host_name:port/form.html

Remember, the CGI script is invoked by the <FORM> tag’s ACTION


attribute once the Submit button has been clicked on.

Note – The mod2-forms/examples/ directory contains a copy of the


form.html HTML form and form.pl script.

Forms Processing With Servlets 2-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

Forms and Servlets

The HTML form used earlier in this module can also be used in a form
servlet solution. The only item in this HTML form that must be
changed is the value for the ACTION attribute within the <FORM> tag
itself. Currently the form launches a CGI script called form.pl:
<FORM METHOD="POST" ACTION="/cgi-bin/form_info.pl">

Modify the ACTION tag to contain the name of the servlet, either
relative to the server_root or as a complete URL. For example:
<FORM METHOD="POST"
ACTION=http://fuggles:8080/servlet/SimpleFormServlet">

2-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

Servlet Code
The following sample is the source code for a SimpleForm servlet that
is invoked by an HTML form and returns the form data to the
browser.
1 import java.io.*;
2 import java.util.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5
6 public class SimpleForm extends HttpServlet {
7
8 public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,IOException {
9
10 Enumeration keys;
11 String key;
12 String value;
13 String title;
14
15 res.setContentType("text/html");
16 PrintWriter out = res.getPrintWriter();
17 out.println("<HEAD><TITLE>
SimpleFormServletOutput</TITLE></HEAD><BODY>");
18 out.println("<h1> SimpleFormServlet Output </h1>");
19 out.println("<P>This is output from SimpleFormServlet.\n");
20
21 keys = req.getParameterNames();
22 while (keys.hasMoreElements()) {
23 key = (String) keys.nextElement();
24 value = req.getParameter(key);
25 out.println("<P>" + key + ": " + value);
26 }
27 out.println("</BODY>");
28 out.close();
29 }
30
31 public String getServletInfo() {
32 return "A simple form servlet";
33 }
34 }

Forms Processing With Servlets 2-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Servlet

HTTPServlet Service Methods


As discussed earlier, there are several HTTP methods supported by the
HTTP protocol (such as GET and POST). The HTML form, used in this
example, generates an HTTP POST using the method=POST form
attribute.

In turn, HttpServlet provides service methods that correspond to each


of the HTTP methods. This example overrides the doPost method to
handle HTTP POSTs (line 8). A servlet must override at least one of the
HttpServlet service methods—usually the one that corresponds to the
type of HTTP method used in the request. A servlet’s service method
is called for each request to the servlet.
✓ There is additional information on service methods in Module 3, “Servlet Life Cycle.”

2-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

HTTPServlet Service Methods (Continued)


HttpServlet service methods are:

● doGet. Override this method if HTTP GET requests are to be


supported by your servlet. Overriding the doGet method
automatically provides support for HEAD operations. Where
practical, the getLastModified method should also be
overridden, to facilitate caching the HTTP response data by the
client. This may improve performance by enabling more efficient
conditional GET support.
✓ A servlet can override more than one HttpServlet service method.

● doPost. Override this method if HTTP POST requests are to be


supported by your servlet.

● doPut. Override this method if HTTP PUT requests are to be


supported by your servlet.
✓ PUT modifies content on the server. Most people do not implement PUT.

● doDelete. Override this method if HTTP DELETE requests are to


be supported by your servlet.
✓ DELETE modifies content on the server. Most people do not implement DELETE.

● doTrace. The default implementation of doTrace causes a


response with a message containing all of the headers sent in the
TRACE request. The doTrace method is not typically overridden.

● doOptions. The default implementation of doOptions


automatically determines what HTTP options are supported
between the Web server and browser and returns the information
to the browser. The doTrace method is not typically overridden.

Forms Processing With Servlets 2-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

HTTPServlet Service Methods (Continued)


● service. This service method is a standard Servlet.service
method which accepts HTTP requests. Override service if you
want your servlet to handle HTTP requests in a “generic manner.”
For example, the service methods listed previously will be invoked
only if there is user interaction on the browser (such as a button
being clicked to submit a form). You can use the generic service
method to respond to requests that did not require user
interaction, such as calling a servlet with a server side include
(SSI).
✓ The standard service method can also be used to receive all request types and then
invoke other service methods, such as doPost and doGet, based on the type of request.

✓ Server side includes are a mechanism for calling CGI scripts or servlets within a Web
page. A server side include calls the script or servlet, embedding the response (if
applicable) in the Web page directly after the server side include.

Note – The service method provided by HttpServlet supports


standard HTTP requests by dispatching them to appropriate methods:
the methods previously listed. The service method for an HttpServlet
is not typically overridden.

Each of these service methods receives a request, in the form of an


HttpServletRequest object, and returns a response in the form of an
HttpServletResponse.
✓ HttpServletResponses were discussed in Module 1, “Servlet Basics.”

✓ The service method can be overridden to provide handling for a generic invocation of a
servlet (server side include) or to reimplement how the servlet acts based on the HTTP
method type. HttpServlet automatically redirects the handling from the service method to
the appropriate helper method (doPost and so on).

2-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Servlet

Setting Content Type


As mentioned previously, the servlet sets the content type through the
response.setContentType method prior to parsing the request data
(line 15).

Forms Processing With Servlets 2-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Servlet

Parsing the Request


HttpServletRequest provides access to HTTP header data, such as
any cookies found in the request and the HTTP method, and a request
body or parameters.

There are several ways to parse the data in an HttpServletRequest.


This example uses getParameterNames and getParameter (lines 21
and 24). The options you choose depends on how the HTTP method is
generated for the request (such as a GET or POST).

For All Requests

Use getParameterNames and getParameterValues for any HTTP


method. The getParameterNames method is used if you do not know
the names of the parameters being passed. In the example,
getParameterNames is used because the servlet is designed to iterate
through the parameters for any form.

2-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

Parsing the Request

For All Requests (Continued)

The getParameterNames method saves the names in an Enumeration


object. Normally, getParameterNames is not needed as servlets are
usually designed to handle parameters in a specific way for a specific
form. The getParameterValues method accepts the name of a
parameter as a String and returns an array of parameter values. This
method is useful when handling parameters whose names have
multiple values.
✓ This is a benefit over CGI, as CGI has to do much more work to ensure that all of the
values, in a multiple-value parameter, are retrieved for a given parameter name.

The getParameter method accepts the name of a parameter as a


String and returns an individual value.
✓ The Java Web Server 1.1 documentation states that getParameter is going to be
deprecated. However, JavaSoft™ had stated that this was changed and getParameter was
going to remain in future servlet API releases.

For an HTTP GET Query String

HTTP GET uses a portion of the URL to send parameters. For example:
http://fuggles:8080/servlet/Survey?name=skiing&level=1&years=15

The parameter portion of a URL, appearing after a question mark (?),


is called a query string. The query string will be put in a shell
environment variable, within the CGI scripts environment, called
QUERY_STRING, when a request is received by a Web server.

The getQueryString method can be used to get the entire query


string held in the environment variable. The parseQueryString
method can be used to parse the individual values within the query
string and put these values into a hashtable. These methods are
normally used if you are submitting individual values, each separated
by a question mark, as part of the URL to the servlet. Use
getParameterNames and getParameterValues to parse the request if
a query string consists of name=value settings.

Forms Processing With Servlets 2-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

Parsing the Request

For HTTP POSTs With Binary or Text (Localized) Data

● Use request.getReader to get a BufferedReader to parse


localized request data.

● Use request.getInputStream to get a ServletInputStream to


parse a binary request data. ServletInputStream contains one
method, readline, which accepts a byte buffer used to contain the
data, a starting offset into the data, and the maximum number of
bytes to read. The following code fragment demonstrates the use
of a ServletInputStream and the readLine method:
1 int buffsize = 1024*8;
2 ...
3 ServletOutputStream out = res.getOutputStream();
4 ...
5 ServletInputStream in = req.getInputStream();
6
7 int contentLength = req.getContentLength();
8 byte[] content = new byte[contentLength];
9 int result;
10 int totalRead = 0;
11
12 try {
13 result = in.readLine(content, 0, content.length);
14 while (result != -1) {
15 totalRead += result;
16 result = in.readLine(content, totalRead,buffsize);
17 }
18 } catch (IOException ioe) {
19 getServletContext().log(ioe, "Error in EchoServlet");
20 }
21 out.write(content, 0, totalRead);
22 out.flush();
✓ Lines 13–16 can be substituted with a more direct approach: in.readline(content).

2-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
An Example Form-Processing Servlet

Parsing the Request

For HTTP POSTs with Binary or Text (Localized) Data (Continued)

In the previous code fragment:

● A ServletInputStream is created from the request (line 5).

● The length of the request is determined using


req.getContentLength (line 7).

● A byte array, called content, is created to hold the data in the


request body (line 8).

● The in.readLine method is used to read each line from the


request and fill the result buffer. The readLine method returns a
negative one (-1) when the end of the buffer has been reached
(lines 13-16).

● A PrintWriter’s write method, called out.write, is used to


write the characters in the PrintWriter (lines 21–22).

Note – This example code fragment comes from the EchoServlet


included with Java Web Server. The mod2-basic/examples/ directory
contains a copy of the EchoServlet.java source file.

CGI Variables and Equivalent Servlet APIs


A Web server stores some HTTP request data, such as a query string,
in CGI environment variables within the shell where the CGI script
was executed. Appendix C contains a list of common CGI variables
and the servlet APIs used to extract the equivalent data.
✓ JavaSoft suggests using BufferedReaders and PrintWriters to support the Unicode
character sets.

✓ There are other methods in the servlet API for parsing HTTP request data. However, these
are the methods that are recommended by JavaSoft.

Forms Processing With Servlets 2-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Servlet

Returning a Response
In the example form-processing servlet, the names of the request
parameters are saved in an Enumeration object (lines 21–24). The,
getParameterValue method is used to extract the value for each name
in the Enumeration object. The PrintWriter’s println method is
used to return to a response (lines 16, and 25).

2-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

An Example Form-Processing Servlet

Displaying Information About a Servlet


The example form-processing servlet also overrides the
getServletInfo method to provide information about the servlet to
the Web server (lines 30–31). This information can include the servlet’s
description, author, and version number. By default, getServletInfo
method returns null. While you are not required to override this
method, it is strongly recommended that you do so.
✓ The getServletInfo method is used to provide information about a servlet to the Web
server. Some example information are author, version, and a brief description.

Forms Processing With Servlets 2-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

Invoking the Example Form-Processing Servlet

You can invoke your servlet with a Web browser once you have placed
your HTML page in the server_root/public_html directory, and
your servlet in the server_root/servlets/ directory. You can type
the following in your URL locator to invoke the form.html page from
your Web browser:
http://host_name:port/form.html

Remember that the servlet, specified with the <FORM> tag’s ACTION
attribute, is invoked once the Submit button has been clicked.

Note – The mod2-forms/examples/ directory contains a copy of the


form.html, and the SimpleForm.java servlet source and .class file.
A special SnoopServlet is also provided. SnoopServlet echoes
information about HTTP GET and POST requests back to a Web
browser. This servlet is useful for learning the contents of HTTP GET
and POST requests.

2-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

Review of Form Servlets

Developing form and servlet solutions involves designing both the


HTML form and the servlet used to process form data. This is
accomplished through the following steps:

● Create an HTML form.

● Modify a form’s ACTION tag to contain the name of the servlet,


either relative to the server_root, or as a complete URL.

● Subclass the HttpServlet class by extending HttpServlet.

● Override at least one of HttpServlet’s service methods to accept


servlet requests. The example servlet uses doPost because the
HTTP POST method is designed to handle larger amounts of data
than an HTTP GET method. Other service methods are doPut,
doDelete, doTrace, doOptions, and service.

● Use setContentType to set the content type of the response.

Forms Processing With Servlets 2-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2

Review of Form Servlets

● Parse the request:

▼ Use getParameterNames and getParameterValues for any


HTTP method. The getParameterNames method returns an
Enumeration object containing parameter names. The
getParameterValues returns an array of values for a given
parameter name. Finally, getParameter returns a single value
for a given parameter name.
▼ The getQueryString method can be used to get the query
string portion of a URL. The parseQueryString method can
be used to parse the individual values within the query string
and put these values into a hashtable. These methods are
normally used if you are submitting individual values, each
separated by a question mark, as part of the URL to the servlet.

▼ Use getReader to get a BufferedReader to parse localized


request data.

▼ Use getInputStream to get a ServletInputStream to parse


binary request data.

2-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Review of Form Servlets

● Use response.getPrintWriter, for text data, or


response.getServletOutputStream, for binary data, to submit a
response.

● Use the PrintWriter or ServletOutputStream’s println


method to generate dynamic HTML.

● (Optional) Override the getServletInfo method to provide


information about the servlet to the Web server.

Forms Processing With Servlets 2-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing Form-Processing Servlets

Exercise objective – Create, configure, and invoke a basic form-


processing servlet. Create a feedback form and form-processing
servlet.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html for


help with the servlet API.

2-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing Form-Processing Servlets

Tasks

Creating BasicForm.java

1. From your home directory, change directory to mod2-


forms/lab/.

2. Open the BasicForm.java file in a text editor.

3. The BasicForm.java file contains a few comments and a


declaration for the BasicForm class. Insert code in
BasicForm.java to do the following:

▼ Handle an HTTP protocol POST method by overriding the


doPost service method.

▼ Set the content type (supplied).

▼ Extract the request data, generated by the BasicForm.html


file, from the HttpServletRequest using the
getParameterValue method. The HTML file is supplied.

▼ Write the data from the BasicForm.html file to a file


(supplied).

▼ Close the file (supplied).

▼ Get a PrintWriter to return data back to the Web browser.


(supplied).
▼ Respond to the client after writing form data to the file.
(supplied).

▼ Provide information about the servlet to the Web server.

4. Save the BasicForm.java file after you have made changes.

Forms Processing With Servlets 2-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing Form-Processing Servlets

Tasks

Creating BasicForm.java (Continued)

5. Generate a BasicForm.class file.

% javac BasicForm.java

Note – The javac compiler generates the error message Note:


BasicForm.java uses a deprecated API. Recompile with -deprecation
for details if you use the getParameter API. You can disregard this
warning. The getParameter API will not be deprecated in the next
release of the servlet API.

6. Copy Basicform.class to the server_root/servlets directory.

7. Copy BasicServlet.html to the server_root/public_html


directory.

2-38 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing Form-Processing Servlets

Tasks

Configuring and Invoking BasicForm.java

1. Add BasicForm to Java Web Server. Refer to Appendix B, “Using


Java Web Server,” for more information.

2. Close the Java Web Server Web Service screen.

3. Load the BasicForm.html file by typing the following URL in


your Web browser:

http://host_name:8080/BasicForm.html

The BasicForm form should be displayed. This form uses the


ACTION attribute to invoke the BasicForm servlet.

4. Fill out the form and click on the Submit button. The Submit
button sends the data to the BasicForm servlet. You will receive a
thank you reply once the data has been saved on the Web server.

Forms Processing With Servlets 2-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing Form-Processing Servlets

Tasks

Creating a Feedback Form and Form-Processing Servlet

1. Create a feedback form.

2. Create a servlet that accepts the feedback information as a request


and stores this information in a file.

3. Return the information to the browser with a thank you note.

2-40 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Exercise: Developing a Form-Processing Servlet

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

Forms Processing With Servlets 2-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ List the two parts of a form-processing solution

❑ Identify the two primary tags used for building HTML forms

❑ List the three attributes used in the <FORM> tag

❑ Explain the seven HTTP method types

❑ Identify how to invoke a CGI script or servlet from an HTML form

❑ List the seven HttpServlet service methods

❑ Explain the differences among getParameterNames,


getParameterValues, getParameter, getQueryString,
parseQueryString, getPrintWriter, and
getServletOutputStream servlet APIs

❑ Identify the use of the getServletInfo method

❑ Write a form-processing servlet

2-42 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
2
Think Beyond

A servlet can receive all types of parameters, from form data to file
and path information, which are required by the servlet to store form
data. It is inefficient to provide a servlet with certain information, such
as file and path information, each time the servlet is called. How do
you think the servlet API handles this type of servlet initialization
information?

Forms Processing With Servlets 2-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Servlet Life C ycle 3

Course Map
This module provides an in-depth discussion of a servlet’s life cycle.
This discussion includes various development issues relative to each
stage in the life cycle.

Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

3-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


the topics presented in this module.

Servlet also provides an init and destroy method that your servlet
can override. Why might you override these methods?

✓ The init method is used for initialization while the destroy method is used to “tear down”
the items initialized in the init method.

As mentioned, a servlet’s service routine is called, in its own thread,


for each client request. What are some of the concurrency issues a
servlet developer might face when developing a servlet?
✓ Class variables are critical data. They can be affected through any request to the servlet.
These variables must be protected in some way.

✓ Access to files such as database records or text files can be accessed by multiple clients
and must also be protected in some way.

3-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Objectives

Upon completion of this module, you should be able to

● List the four steps in a servlet’s life cycle

● Identify the three locations where servlets load

● Describe, in one sentence, the purpose of the init method

● Explain the use of the getInitParameter and


getInitParameterNames APIs

● Describe the two options for handling concurrency issues caused


by multiple service routines

● Describe, in one sentence, the purpose of the destroy method

● Explain how to manage service threads at service termination

● Modify a form-processing servlet to handle initialization


parameters and long-running threads

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Java Servlet Tutorial. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/
servlet_tutorial.html.

● Developing Java Servlets. Crawford, William. [Online]. Available:


http://webreview.com/97/10/10/feature/index.html.

● Servlets & Friends. Sagar, Ajit. Java Developer’s Journal (February).

Servlet Life C ycle 3-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

Servlet Life Cycle

There are four steps within a servlet’s life cycle. The first step is the
actual loading and instantiation of the servlet, the creation of a servlet
instance, by a service. This step is followed by the invocation of three
life cycle methods: init, service, and destroy.

3-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

Loading and Instantiating a Servlet

Class Loaders
A system class loader or special Java Web Server class loader will load
and instantiate your servlet classes (either automatically when Java
Web Server starts, or when the servlet is initially referenced). The class
loader that is used is dependent on the location of your servlet’s
classes.
✓ A class loader is responsible for loading your servlet. The class loader used will depend
on the servlet’s .class file location, adhering to the security restrictions put in place by
the Virtual Machine (VM) and Java Web Server.

Servlet Life C ycle 3-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Loading and Instantiating a Servlet

Servlets on the CLASSPATH


You can put your servlets and supporting classes in the CLASSPATH.
Servlets in the CLASSPATH will be loaded by a system class loader.
However, servlets in the CLASSPATH are not automatically reloaded
when they have changed (been recompiled).

Note – Servlets will cause a decrease in performance when initially


loaded or reloaded by a Web server.

✓ Generally, it is recommended that you load servlets from the /servlets directory.
However, due to security restrictions, you may not have access to items like native
methods.

✓ Some startup scripts with servlet runners might or might not start the Java interpreter
with the following command: java -classpath /somepath:/someotherpath, causing the
environment variable to be ignored. With Java Web Server all classpath manipulation is
performed by startup scripts. The trick is understanding how the runtime for any servlet
runner works.

Servlets in server_root/servlets/
The server_root/servlets directory is not in Java Web Server’s
CLASSPATH. A special Java Web Server class loader is used to create
servlets from this directory. Java Web Server will reload servlets from
this directory when their time stamp is updated (reflecting a change in
the servlet’s code).
✓ Your servlets may not have access to native methods when they are in the /servlets
directory. This indicates a difference in the way that the Java Web Server and system
class loaders handle security. See the security module for more information.

Remote Servlets
You can load servlets from a remote location, such as another Web
server. To load servlets remotely, you must define a codebase in
addition to the servlet’s class name (for example,
http://nine.eng/classes/foo/). Refer to Appendix B, “Using Java
Web Server,” for information on configuring remote servlets.

3-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The init Method

Overview
When a service loads a servlet, it invokes the servlet’s init method.
The init method prepares the servlet for service requests by
establishing resources that a servlet manages. You must override the
init method if your servlet needs to perform some one-time
initialization. Furthermore:

● The init method is called only once; the service will not call init
again unless it is reloading the servlet.

● The init method cannot be re-executed unless its destroy


method has been called by the service to remove the servlet.

● As soon as the init method returns, the servlet can receive client
requests through its service method.

● Even though most servlets are run in multithreaded services, there


are no concurrency issues during servlet initialization because the
service calls init once.

Servlet Life C ycle 3-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The init Method

An Example init Method


The following code is an example of a basic init method. This
method is used to get initialization parameters from Java Web Server.
1 public class MyServlet extends HttpServlet {
2 public void init(ServletConfig conf) throws ServletException {
3
4 super.init(conf);
5 log("PhoneServlet.initialize: enter");
6
7 String fileName = getInitParameter("phonelist");
8 if (fileName == null) {
9 return;
10 }
11
12 log("PhoneServlet.initialize: filename = " + fileName);
13 }
14 ...
15 }
✓ The getInitParameter and getInitParameterNames methods call config.getInitParameter.

3-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The init Method

An Example init Method

Accepting ServletConfig

The init method accepts a ServletConfig object as a parameter (line


24). The ServletConfig object contains initialization parameters and
configuration methods.

The init method should throw an UnavailableException exception


if, for some reason, the servlet’s required resources cannot be
established (for example, a required network connection cannot be
created), or an initialization error occurs that will not allow the servlet
to handle requests properly (line 24).
✓ The servlet context can be used to obtain the MIME type, path, servlet’s name, and so
forth.

Servlet Life C ycle 3-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The init Method

An Example init Method

Saving ServletConfig

The init method should save the ServletConfig object, so you can
retrieve it later using getServletConfig (line 26). The simplest way
to save the object is to have the your init method call super.init
(with the ServletConfig object as a parameter). If you do not call
super.init, you should store the ServletConfig object yourself, and
override the getServletConfig method so that it can obtain the
object from its new location.

Retrieving Initialization Parameters

The ServletConfig object provides two methods for accessing


initialization parameters. These are:

● getInitParameter

● getInitParameterNames

The getInitParameter method takes the parameter name as an


argument (line 29). For example:
String resultsDir = getInitParameter("phonelist");

The getInitParameterNames method is used to get the parameter


names.

3-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The Init Method

Configuring Initialization Parameters


Servlet initialization parameters are configured within a Web Server.
This process differs with each Web server. The Java Web Server
provides a property editor that allows you to define parameter names
and values for retrieval by a servlet’s init method. Refer to Appendix
B, “Using Java Web Server,” for information on adding initialization
parameters.

Note – Initialization parameters are useful for defining static


information such as database names, an RMI registry server name, and
log file names.

Servlet Life C ycle 3-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The service Method

A servlet is ready to handle client requests after being initialized by a


service. Client requests are processed by a servlet’s service methods.
Each client’s request has its call to a service method run in its own
servlet thread: the method receives the client’s request, and sends the
client its response.
✓ It may be worth repeating that each time a service method is called, it runs in its own new
thread. Generally, you do not want to create new threads within a service method.

When a service method is called, it receives two objects:


ServletRequest and ServletResponse. ServletRequest is used to
communicate from the client to server. Conversely, ServletResponse
is used to communicate from the server to the client.

ServletRequest
ServletRequest gives a servlet access to information such as
parameter names and values, the protocol (scheme) used by the client,
the names of the remote host that made the request, the server that
received the request, and an input stream.

3-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The service Method

ServletResponse
ServletResponse provides an output stream and a writer, through
which the servlet can send the reply data. ServletResponse also
allows the servlet to set the content length and MIME type of the reply.

Concurrency Issues
Servlets can run multiple service methods simultaneously. Therefore,
service methods must be thread-safe. For example, if the service
method updates a field in the servlet object, such as a class variable,
that access should be synchronized.

Servlet Life C ycle 3-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The service Method

Threading code falls into one of two classifications: multithreaded-safe


or multithreaded-hot.

Multithreaded-Safe Servlets

Definition

Multithreaded-safe code means that multiple threads can access and


change volatile data such as class variables, without corrupting that
data. Multithreaded-safe does not necessarily mean that the code is
written for optimal performance. In fact, multithreaded-safe code is
not affected if a user’s request is blocked by another user for an
extended period of time.

3-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The service Method

Multithreaded-Safe Servlets

Recommendations for Code

When writing multithreaded-safe code for a servlet:

● Make sure that methods and variables that do not need to be


publicly accessible are marked with the appropriate access
modifier (private, protected, or package).

● Ensure that all instance methods that access critical data are
synchronized.

● Class variables are considered critical data. Create access methods


to access class variables.

An Example Synchronized Access Method

For example, several servlets could be writing to the same file at the
same time. If the writing is not synchronized, the data that is written
may not appear in the proper order. Following is a service method
that calls a synchronized access method to write to a file:

1 public class LogServlet extends HttpServlet {


2 public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException {
3 String data = "Hello World";
4 this.writeToFile(data);
5 }
6
7 private synchronized writeToFile(String data) {
8 // code that writes to the file
9 }
10 }
✓ Just as in creating a multithreaded Java software solution, use synchronized blocks to
protect critical data.

Servlet Life C ycle 3-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The service Method

Multithreaded-Hot Servlets

Definition

Multithreaded-hot code is multithreaded-safe code that is optimized for


performance.

Recommendations for Code

When writing multithreaded-hot code for a servlet:

● Ensure that your code is multithreaded-safe.

● Ensure that several threads can simultaneously call and make


modifications to the same object safely. In other words, threads
should not block each other for extended periods of time.
✓ Java Web Server code is multithreaded-hot; multiple service methods can run
concurrently without blocking.

✓ The distributed computing module discusses multithreaded-hot issues in relation to


database access by multiple clients.

3-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The service Method

SingleThreadModel
Your servlet may implement the SingleThreadModel interface if a
service should not run multiple servlet service methods concurrently.
SingleThreadModel guarantees that multiple instances of the servlet
are created and individually called for each request. An example of a
class implementing SingleThreadModel is
1 public class FormServlet extends HttpServlet implements
SingleThreadModel {
2 ...
3 }

SingleThreadModel operates by ensuring that only one thread-


service method is run per servlet instance. If an additional request is
received, a new instance of servlet is created.
✓ This module and Module 9 address multithreaded-safe code. Module 4 focuses on
multithreaded-hot code.

Servlet Life C ycle 3-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The destroy Method

Overview
When a service unloads a servlet, it calls the servlet's destroy method.
The destroy method should undo any initialization work and
synchronize persistent data with the current in-memory state of the
servlet.

While most servlets that override init also override destroy to undo
the initialization, this is not required. For example, a servlet that uses
the init method to get a parameter, such as a file name, does not need
to override destroy because a file name is not a resource that typically
requires clean-up.
✓ The forms module discusses the destroy method in further detail.

✓ Other uses for destroy are: closing a database, cleaning up spawned threads, and closing
files and resources.

3-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The destroy Method

An Example destroy Method


The following code is an example of a basic destroy method that
closes a database connection that was presumably opened in a
servlet’s init method.
1 public void destroy() {
2 try {
3 con.close();
4 } catch (SQLException e) {
5 while(e != null) {
6 getServletContext.log("SQLException: " + e.getSQLState()
+'\t' + e.getMessage() + '\t' + e.getErrorCode()
+ '\t');
7 e = e.getNextException();
8 }
9 }
10 }

Servlet Life C ycle 3-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The destroy Method

An Example destroy Method

Uninitialization

The example uses the connection.close method to close a JDBC


connection. SQLException is caught in the event that the connection
cannot be closed.

Writing Exceptions to Log Files

The example uses the simplified version of the ServletContext’s log


method to get the context for the servlet and print a string to the
server_root/logs/javawebserver/event_log.

Concurrency Issues

The destroy method is run once. However, when the destroy


method is invoked, several service threads might still be running.

3-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The destroy Method

Handling Service Threads at Servlet Termination


When a service removes a servlet, it typically calls destroy after all
service calls have been completed, or a specified number of seconds
have passed, whichever comes first. If your servlet performs
operations that take a long time to complete (longer than the Web
server’s grace period), service threads could still be running when
destroy is called. You are responsible for making sure that all threads
complete before destroy completes.

A servlet with long-running service requests should keep track of how


many service methods are currently running. Its long-running
methods should periodically poll to make sure that they should
continue to run. If the servlet is being destroyed, the destroy method
should wait for the service methods to complete, in order to provide a
clean shutdown.

Servlet Life C ycle 3-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

The destroy Method

Tasks in Handling Threads


There are four tasks involved in handling threads at service
termination:

● Establish a service counter, shutdown flag, and associated access


methods for these variables.

● Call these methods from the service routine to increment and


decrement the service counter.

● Check the shutdown flag, within the service routine, to ensure


that a long-running operation should perform.

● Set the shutdown flag when the destroy method is called.

3-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The destroy Method

An Example of Handling Service Threads


1 public ShutdownExample extends HttpServlet {
2 private int serviceCounter = 0;
3 private boolean shuttingDown;
4 private int interval = 1000;
5 ...
6
7 // Access methods for serviceCounter
8 protected synchronized void enteringServiceMethod(){
9 serviceCounter++;
10 }
11
12 protected synchronized void leavingServiceMethod() {
13 serviceCounter--;
14 }
15
16 protected synchronized int numServices() {
17 return serviceCounter;
18 }
19
20 // Access methods for shutting Down
21 protected synchronized void setShuttingDown(boolean flag) {
22 shuttingDown = flag;
23 }
24
25 protected synchronized boolean isShuttingDown() {
26 return shuttingDown;
27 }
28 }

Access Methods

In the code example, an instance variable, called serviceCounter,


that counts the number of service methods running is created (line 2).
An indicator of whether the servlet is being destroyed, called
shuttingDown, is also created (line 3). Each variable has its own set of
synchronized access methods (lines 8, 12, 16, 21, and 25).

Servlet Life C ycle 3-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The destroy Method

An Example of Handling Service Threads


29 protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
30
31 // Increment serviceCounter
32 enteringServiceMethod();
33
34 // Your service method code goes here
35
36 // Here’s a long running operation, check the flag
37 for(i = 0; ((i < lotsOfStuffToDo) &&
!isShuttingDown()); i++) {
38 try {
39 longRunningOperation(i);
40 }
41 catch (InterruptedException e) {
42 getServletContext().log (ioe, "Error, couldn’t perform long
running operation");
43 }
44 }
45 // Decrement serviceCounter
46 leavingServiceMethod();
47 }
48

Incrementing and Decrementing Service Counter

The service method handles incrementing the service counter each


time it is entered (line 32). The service method also decrements the
service counter each time it returns (line 46).

Performing the Check

The long-running method checks the isShuttingDown variable, and


interrupts work if necessary (line 37). If isShuttingDown is false,
longRunningOperation method is allowed to execute (line 39).

3-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
The destroy Method

An Example of Handling Service Threads

49 public void destroy() {


50
51 // Check to see whether there are still service
52 // methods running, and if there are, tell them to stop.
53 if (numServices() > 0) {
54 setShuttingDown(true);
55 }
56
57 // Wait for the service methods to stop.
58 while(numServices() > 0) {
59 try {
60 Thread.sleep(interval);
61 }
62 catch (InterruptedException e) {
63 }
64 }
65 }
66 }

Checking Service Counter

The destroy method ensures that all service methods have finished.
The destroy method checks the serviceCounter, and if there are any
long-running methods, sets the shuttingDown variable (line 53–54).
This variable will let the threads still handling client requests know
that it is time to shut down. The destroy method should wait for the
service methods to complete, in order to provide a clean shutdown
(lines 58–64).
✓ Another solution to this code example is to use wait and notify in destroy to wait for
threads rather than the sleep method.

Servlet Life C ycle 3-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

Review of Servlet Life Cycle

Servlets have a life cycle: they load through a class loader, initialize
through the init method, run through the invoker calling service,
and unload through destroy. The summarized items regarding servlet
life cycle are:

● A class loader is used to load servlets, either when the server starts
up (usually user-definable) or when the servlet is initially
referenced.

● The init method can be overridden and used to provide


initialization information to a servlet.

▼ The init method is only called once: the service will not call
init again unless it is reloading the servlet.
▼ The init method cannot be reloaded unless its destroy
method has been called by the service to remove the servlet.

▼ As soon as the init method returns, the servlet can receive


client requests through its service method.

3-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3

Review of Servlet Lifecycle

● The init routine accepts a ServletConfig object which contains


getInitParameter and getInitParameterNames methods for
extracting initialization parameters.

● Initialization parameters are configured within a Web server and


the process differs from Web server to Web server.

● You need to pay attention to thread-safe concurrency issues with


your servlet’s service routine.

▼ Methods and variables that do not need to be publicly


accessible should be marked with the appropriate access
modifier (private, protected, or package).

▼ All instance methods that access critical data should be


synchronized.

▼ Create access methods to access class variables.

▼ There are no concurrency issues during servlet initialization


because the service calls init only once.

Servlet Life C ycle 3-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Review of Servlet Lifecycle

● Your servlet may implement the SingleThreadModel interface if a


service should not run multiple servlet service methods
concurrently.

● The destroy method should undo any initialization work and


synchronize persistent data with the current in-memory data of
the servlet.

● You need to pay attention to thread-safe concurrency issues before


a servlet is destroyed.

▼ Establish a service counter, shutdown flag, and associated


access methods for these variables.
▼ Call these methods from the service routine to increment and
decrement the service counter.

▼ Check the shutdown flag within the service routine to ensure


that a long-running operation should execute.

▼ Set the shutdown flag when the destroy method is called.

3-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Exercise objective – Modify the form-processing servlet to accept a


file name and directory to save form information in. Ensure that the
form-processing servlet handles long-running threads.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

Servlet Life C ycle 3-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Tasks

Creating BasicFormTwo.java

1. From your home directory, change directory to mod3-


lcycle/lab/.

2. Open the BasicFormTwo.java file using text editor.

3. The BasicFormTwo.java file contains a few comments and a


declaration for the BasicFormTwo class. Insert code within
BasicFormTwo.java to do the following:

▼ Extract the resultsDir initialization parameter in the init


method.

▼ Handle an HTTP protocol POST method by overriding the


doPost service method (supplied).

▼ Set the content type (supplied).

▼ Extract the request data, generated by the BasicFormTwo.html


file (included), from the HttpServletRequest using the
getParameterValue method (supplied). Write the data from
the BasicFormTwo.html file to a file (supplied).

▼ Handle writing to the file as a long-running operation.

▼ Close the file (supplied).

▼ Get a PrintWriter to return data to the Web browser (supplied).

▼ Respond to the client after writing form data to the file


(supplied).

▼ Provide information about the servlet to the Web server


(supplied).

3-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Tasks

Creating BasicFormTwo.java (Continued)

4. Save the BasicFormTwo.java file after you have made changes.

5. Generate a BasicFormTwo.class file.

% javac BasicFormTwo.java

6. Copy BasicFormTwo.class to the server_root/servlets


directory.

7. Copy BasicServlet.html to the server_root/public_html


directory.

Servlet Life C ycle 3-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Tasks

Configuring and Invoking BasicFormTwo.java

1. Add BasicFormTwo to Java Web Server. Refer to Appendix B,


“Installing and Starting the Java Web Server,” for more
information.

2. Click on the BasicFormTwo servlet in the hierarchical list of


servlets.

3. Click on the Properties tab to display the Properties card.

4. Click on the Add button to add a new property.

5. Type resultsDir in the Property field.

6. Type servlets/myData.txt in the Value field.

7. Click the Save button.

8. Click on the Configure tab to display the Configure card.

9. Click on Load to load the servlet.

10. Close the Java Web Server Web Service screen.

11. Load the BasicFormTwo.html file by typing the following URL in


your Web browser:

http://host_name:8080/BasicFormTwo.html

You should see the BasicFormTwo form appear. This form uses the
ACTION attribute to invoke the BasicFormTwo servlet.

12. Fill out the form and click on the Submit button. The Submit
button sends the data to the BasicFormTwo servlet. You will
receive a thank you reply once the data has been saved on the Web
server.

3-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Tasks

Configuring and Invoking BasicFormTwo.java (Continued)

13. List the contents of the server_root/servlets/ directory. You


should see a file called myData.txt containing the information
you submitted in the form in step 12.

Servlet Life C ycle 3-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Exercise: Modifying the Form-Processing Servlet

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

3-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ List the four steps in a servlet’s life cycle

❑ Identify the three locations where servlets load

❑ Describe, in one sentence, the purpose of the init method

❑ Explain the use of the getInitParameter and


getInitParameterNames APIs

❑ Describe the two options for handling concurrency issues caused


by multiple service routines

❑ Describe, in one sentence, the purpose of the destroy method

❑ Explain how to manage service threads at service termination

❑ Modify a form-processing servlet to handle initialization


parameters and long-running threads

Servlet Life C ycle 3-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
3
Think Beyond

Can you think of additional, solution-specific, uses for the three life
cycle methods: init, service, and destroy?

3-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Database Access 4

Course Map
Database access is one of the primary uses of CGI scripts and
servlets. This module discusses using a JDBC connection pool to
optimize database access times between a Web browser and Web
server.
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

4-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following question is relevant in understanding the


topics presented in this module.

What issues do you foresee when you implement distributed


technologies in a servlet or Web-based environment?

✓ You will have to deal with connection management, and orientation (servlets as clients or
as servers to other clients)

4-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Objectives

Upon completion of this module, you should be able to

● Identify the components of two-tier and multi-tier architectures

● List three distributed Java technology computing solutions

● List the four steps needed to create a simple database access client

● Identify the two considerations for designing Web-based database


solutions

● Identify the two types of connection lists needed in a connection


pool

● List the basic APIs necessary in a connection pool class

● Update the DBServlet to implement connection management,


quick database access, and thread safety

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JDBC Database Access with Java. Hamilton, Graham, Cattell, Rick,


and Fisher, Maydene. Addison-Wesley. 1997.

● Java IDL Documentation. [Online]. Available:


http://java.sun.com/products/jdk/idl/docs.html.

● Multi Tier Architectures for Database Connectivity. [Online].


Available: http://javaexchange.com/dcb_white.html.

Database Access 4-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Distributed Models

Distributed applications require that computations running in


different address spaces, potentially on different hosts, be able to
communicate. Servlets can take advantage of distributed architectures
by providing an entry point to server-side data and Java applications.
Servlets can be used with distributed frameworks such as common
object request broker architecture/interface definition language
(CORBA/IDL), Remote Method Invocation (RMI), and Java database
connectivity (JDBC).

Two-Tier (Client/Server)
The two-tier model for distributed computing consists of multiple
clients talking to one or more servers. The client, an applet or
application on an end-user machine, talks directly to shared
applications and databases on a server. The client generally performs
some computation and handles items like connection management.

4-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Distributed Models

Two-Tier (Client/Server) (Continued)


Other characteristics of two-tier architectures are:

● Clients are “thick,” meaning they contain code to do computation


and other tasks (business rules or logic).

● The overall architecture is simple, but could lack in efficiency.

● There are only three points of failure.

● They are easy to administrate and control.

Figure 4-1 provides an example of a two-tier system.

Java application
Client machine
JDBC

DBMS-proprietary protocol

Database server
DBMS

Figure 4-1 A Two-Tier System

Multi-Tier
The multi-tier model for distributed computing consists of multiple
clients interacting with one or more servers which, in turn, interact
with one or more additional servers. Generally clients talk to
middleware components (such as servlets on a Web server) which talk
to other tiers such as database servers, application servers, and other
servlets on other Web servers.

Database Access 4-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Distributed Models

Multi-Tier (Continued)
In a multi-tier system, operations like computation and connection
management are performed on the server. Other characteristics of
multi-tier architectures are:

● Clients are “thin,” meaning they do not contain a lot of code.

● The overall architecture is complex, but could be efficient.

● They are possibly easier to maintain.

● They might be easier to swap in device drivers (one central


location).

● They might be more fault tolerant.

● They are complex so there are more points of failure.

Figure 4-2 provides an example of a multi-tier system.

Java applet or
Client machine (GUI)
HTML browser

HTTP, RMI, CORBA, or other calls

Application server
(Java) Server machine (business logic)

JDBC

DBMS-proprietary protocol

Database server
DBMS

Figure 4-2 A Multi-Tier System

4-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Distributed Java Technologies

Three distributed technologies covered in this course are

● Java Database Connectivity (JDBC) API

● Java Remote Method Invocation (RMI) API which is covered in


Module 5

● Common Object Request Broker Architecture (CORBA)


represented by Java Interface Definition Language (IDL) which is
covered in Module 5

Each technology takes full advantage of the Java programming


language as an object-oriented language, and each provides several
benefits over technologies implemented with C and other functional
languages. This module focuses on JDBC distributed technology.
✓ These modules provide an overview of distributed Java technologies. Students are
encouraged to sign up for the SL301 course to learn more about Java RMI, JavaIDL, and
JDBC programming.

✓ Technically, JDBC isn’t really a distributed technology. JDBC enables you to easily create
distributed architectures.

Database Access 4-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Java Database Connectivity (JDBC)

Overview
The JDBC API provides the developer with a means for insulating the
Java technology client program (applet or application) from the
specific databases the client wants to access.

The API provides a set of generic interface classes that are


implemented by a database-specific driver. The application can be
developed as either a two-tier, three-tier, or multi-tier design, and the
driver can be written to access any protocol such as structured query
language (SQL).

Database access is becoming a requirement for most Web-based


systems. Servlets can be used to provide access to large relational
databases, when used in conjunction with Java database connectivity
(JDBC).
✓ JDBC consists of two APIs: an API for developers (generic interfaces) for providing
access to a database and an API for driver vendors for providing specifics on interactions
with their particular database.

4-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Java Database Connectivity (JDBC)

An Example Database Servlet


The code for the DBServlet database access servlet follows. There are
five steps to creating a simple database access servlet: loading the
database driver, establishing a connection to the driver, creating and
executing a query, displaying the results, and closing the connection.
1 public class DBServlet extends HttpServlet {
2 // It is probably more appropriate to read these in as init
3 //parameters or from a properties file.
4 static final String url =
"jdbc:msql://fuggles:1114/mydatabase";
5 static final String jdbcclass =
"com.imaginary.sql.msql.MsqlDriver";
6 static final String user = "";
7 static final String pass = "";
8 static final int initialCons = 5;
9 static final int maxCons = 20;
10 static final boolean block = true;
11 static final long timeout = 10000;
12
13 public void init(ServletConfig config) throws ServletException {
14
15 super.init(config);
16 log("DBServlet.initialize: enter");
17 try {
18 // Load the JDBC driver.
19 Class.forName(jdbcclass).newInstance();
20
21 } catch (Exception e) {
22 e.printStackTrace();
23 String errmsg = e.getMessage();
24 log("Failed:" + errmsg);
25 }
26 }
27
28 public void service(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
29
30 String lname;
31 Connection con = null;
32 PrintStream out = null;

Database Access 4-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Java Database Connectivity (JDBC)

An Example Database Servlet (Continued)


33 ...
34
35 try {
36 // get the connection from the database
37 con = DriverManager.getConnection (url);
38
39 ...
40
41 // create and execute the query
42 Statement stmt = con.createStatement();
43 String query = "SELECT first_name, last_name, comment "
+ "FROM emp_details " + "WHERE last_name='"
+ lname +"'";
44
45 ResultSet rs = stmt.executeQuery(query);
46
47 // print out the result
48 dispResultSet(rs, out);
49
50 rs.close();
51 stmt.close();
52 con.close();
53 ...
54 }
55 }
56 private void dispResultSet(ResultSet rs, PrintStream out)
throws SQLException {
57 int i;
58
59 // metadata can supply information about the schema
60 ResultSetMetaData rsmd = rs.getMetaData();
61
62 // User metadata to print out result set
63 ...
64 }
65 }

4-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Java Database Connectivity (JDBC)

An Example Database Servlet (Continued)


This servlet presents the end user (browser) with a form to fill in with
the last name of an employee for an employee database. DBServlet is
invoked when the data is submitted and queries the database
(mydatabase) for the employee’s record. If found, the employee’s
record is returned to the client browser.

Database Access 4-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Java Database Connectivity (JDBC)

Loading the Database Driver


All database applications must load a database driver. Loading a
driver requires one line of code using the Class.forName API,
provided by java.lang package. The example loads the MsqlDriver
(line 19) with the line
Class.forName(jdbcclass).newInstance();

The jdbcclass variable points to the name of the class to load (line 5).
✓ You could also use new MsqlDriver to create a driver instance.

4-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Java Database Connectivity (JDBC)

Establishing a Connection to the Database


All database applications need to establish a connection to the
database after the database driver is loaded. This is accomplished
through the DriverManager.getConnection provided by
java.sql.DriverManager. The example establishes a connection (line
37) with the line
con = DriverManager.getConnection(url);

The variables url and con are defined on lines 4 and 31, and 37,
respectively.

The URL will always start with jdbc:. The vendor documentation for
the JDBC driver will describe the syntax for the remainder of the URL.
✓ The getConnection method accepts a string which describes url, username, and
password.

Database Access 4-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Java Database Connectivity (JDBC)

Creating and Executing a Query


After the database driver is loaded and a connection established, an
application can use the connection to create JDBC statements that pass
SQL statements to the database. The example creates a statement (line
42), builds the SQL statement (43), and executes the query (45) with
the following lines of code:
Statement stmt = con.createStatement();
String query =
"SELECT first_name, last_name, comment"
+ "FROM emp_details " + "WHERE last_name='"+
lname +"'";
ResultSet rs = stmt.executeQuery(query);

ResultSet will contain the results (rows) of the query, if the query
information is found.

4-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Java Database Connectivity (JDBC)

Parsing and Displaying the Results


The example creates a ResultSetMetaData object from the result of
the query (line 45). The ResultSetMetaData object provides
information about the ResultSet object, including the result data
itself. ResultSetMetaData contains several methods to parse the
resulting data prior to returning the data in a response to the client.
✓ Again, this module provides an overview of database access using JDBC. Students are
encouraged to sign up for the SL301 course to learn more about Java JDBC programming.

Database Access 4-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Java Database Connectivity (JDBC)

Closing the Connection


A connection should be closed once it is no longer needed. DBServlet
is done with a connection (line 52). The servlet also closes the
ResultsSet and Statement on lines 50 and 51, respectively.

Note – The mod4-jdbc/examples/ directory contains a copy of the


DBServlet source and .class files. Before you can try this servlet,
you must edit DBServlet and modify the value for the url variable.
This variable must reference the hostname of the machine where the
database is running. Copy DBServlet.class to
server_root/servlets once you have made this modification and
have recompiled the source file. The following last names are valid for
testing DBServlet: Smith, McNealy, Colorado, Cruz, and
Presson.

4-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

JDBC and Servlets

While DBServlet demonstrates how to create a basic database access


servlet, it functions as if performance is unimportant by creating a new
connection for every request. It generally takes one to three seconds to
establish a database connection. While connection time may compose
only a small portion of the time required for large database queries,
small, frequent queries require very short connection times to be
efficient (especially if there are a lot of clients trying to access the same
database). These types of queries can include those that retrieve HTML
text, process form data, or create dynamic HTML from database data.

Concurrency is also a common problem when handling multiple users


accessing the same data. When accessing a database, all connections
must be thread safe to prevent data corruption or lock-ups.
DBServlet‘s connections are thread safe because they are created as
local variables within the service routine. However, as stated
previously, creating a new connection for each request is inefficient.

Database Access 4-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Connection Pools

Overview
The best solution to the timing and connection problem is to create a
pool of persistent (reusable) connections that will be used by a servlet
as needed. This pool of connections should be managed by a separate
object called a connection pool.
✓ Other terms for a connection pool are “connection broker” and “connection manager.”

Generally, a connection pool would manage a set of connections,


watch for locked or corrupted connections, perform housekeeping
tasks (such as maintaining arrays of connections available or in use),
and possibly log events.

4-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Connection Pools

Items to Consider
Items to consider when developing a connection pool are:

● The connection pool must detect and recover from failures on


individual connections.

● The connection pool developer must determine the number of


connections that will be created (and whether this number is static,
dynamic, or user configurable).

● The connection pool developer must decide whether the pool will
allow blocking, which would cause a client to wait until a
connection is free.

● The connection pool developer must decide whether the pool


should log events and errors.

Database Access 4-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Implementing a Connection Pool

There are two components of the basic connection pool servlet


solution:

● The servlet. The servlet is also referred to as the connection pool


client because it requests connections from the connection pool
object.

● The connection pool.

4-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Implementing a Connection Pool

A Connection Pool Client


The connection pool and connection pool servlet represent a middle
tier in a multi-tier solution; they lie between the browser and the
connection pool object. With the addition of a connection pool, a
servlet would no longer have to create and tear down individual
connections. Instead, the servlet would:

1. Load the database driver

2. Create an instance of the connection pool.

Database Access 4-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Implementing a Connection Pool

A Connection Pool Client (Continued)


3. Request a connection from the connection pool. The connection
pool could implement two options if all of the connections are
currently being used. It would allow

▼ For blocking, forcing the client to wait for a connection to be


released by another service thread.
▼ Dynamic creation of new connections up to a pre-defined
maximum amount of connections

4. Use the connection to initiate a query.

5. Return the connection to the pool.

6. Tear down the entire connection pool when the servlet is


destroyed.

4-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Implementing a Connection Pool

An Example Connection Pool Client Servlet


The following code fragment shows several comment lines to illustrate
the order in which a connection pool servlet will perform database-
related operations. The code has been supplied because the operation
is different from the operation in the DBServlet example.

1 // Load the JDBC driver


2
3 // Instantiate a connection pool
4 ConnectionPool cp = new ConnectionPool(url, user, pass, initialCons,
maxCons, block, timeout);
5
6 // Get a connection from the connection pool
7 con = cp.getConnection();
8
9 // Submit a query using the connection
10
11 // Release the connection to the pool
12 cp.releaseConnection(con);
13
14 // Close all of the connections
15 cp.closeAll();

Which lines of code in the example should be in init, service, or


destroy?

✓ Generally you want to load the driver and instantiate the pool in init; get a connection;
submit a query, return the connection in service; and close all of the connections when
the servlet is destroyed.

✓ Why does ConnectionPool take initialCons and maxCons as parameters? Because it has
the capability of increasing the number of connections it maintains should the pool run
out of connections.

✓ Notice that the ConnectionPool also takes block and timeout. This indicates that there will
be some sort of blocking functionality within the pool.

Database Access 4-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

The ConnectionPool API

The connection pool accomplishes some of the basic database tasks


such as creating and closing connections. This course contains the
source and .class file for ConnectionPool in
mod5-distrib/examples/.
✓ Students may want to create their own connection pool classes. This class is provided as
an example.

4-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The ConnectionPool Constructor


The ConnectionPool class contains one constructor which accepts
seven values. A fragment of the ConnectionPool constructor is
shown here.

1 public ConnectionPool(String url, String user, String password,


int initialCons, int maxCons, boolean block, long timeout)
throws SQLException {
2 ...
3
4 // Create vectors large enough to store all the connections we make
now.
5 free = new Vector(initialCons);
6 used = new Vector(initialCons);
7
8 // Create some connections.
9 while (numCons < initialCons){
10 addConnection();
11 }
12 }

The example ConnectionPool contains one constructor which sets up


two connection vectors to hold available (free) and currently
allocated (used) connections.

The constructor also calls addConnection to create an initial number


of connections for the pool (initialCons).

Database Access 4-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The addConnection Method


The addConnection method adds elements (connections) to the free
vector. The addConnection method shown here.

1 private void addConnection() throws SQLException {


2 free.addElement(getNewConnection());
3 }

Connections are actually created by calling the getNewConnection


method (line 2).

4-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The getNewConnection Method


The getNewConnection method creates Connections. The
getNewConnection method is shown here
1 private Connection getNewConnection() throws SQLException {
2
3 Connection con = null;
4
5 System.out.println("About to connect to " + url);
6 try {
7 con = DriverManager.getConnection(url);
8 } catch (Exception e) {
9 e.printStackTrace();
10 }
11 ++numCons;
12 return con;
13 }

The getNewConnection method is a private method. This method


calls the DriverManager.getConnection API, provided by
java.sql.DriverManager, to create a new connection for the pool
(line 7).
✓ Students should notice that this is the same mechanism used by DBServlet.

Database Access 4-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The getConnection Method


The database access servlet calls getConnection to get a connection
from the connection pool. A fragment of the getConnection method
is shown here.

1 public synchronized Connection getConnection(boolean block, long


timeout) throws SQLException {
2
3 if (free.isEmpty()) {
4
5 // None left, do we create more?
6 if (maxCons <= 0 || numCons < maxCons) {
7 addConnection();
8 }
9
10 else if (block) {
11 ...
12
13 // Did anyone release a connection while we were waiting?
14 if (free.isEmpty()) {
15 if (maxCons <= 0 || numCons < maxCons) {
16 addConnection();
17 } else {
18 throw new SQLException("Timeout waiting for a
connection to be released");
19 }
20 }
21 } else {
22 // No connections left and we don't wait for more.
23 throw new SQLException("Maximum number of allowed
connections reached");
24 }

4-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The getConnection Method (Continued)


25 }
26 // If we get this far at least one connection is available.
27 Connection con;
28
29 synchronized (used) {
30
31 con = (Connection)free.lastElement();
32 // Move this connection off the free list
33 free.removeElement(con);
34 used.addElement(con);
35 }
36 return con;
37 }

The getConnection method supplies a connection pool client with a


connection. This method attempts to supply the connection from the
vector of free connections (line 3, 31–34) . If no connections are
available, getConnection attempts to create new connection (lines 6–
8). If the maximum number of connections, allowed in the pool has
been reached, getConnection checks the block flag and blocks if the
it is set (line 10).

The blocking if/else statement waits for a defined amount of time


and then checks to see if a connection has been returned to the free
Vector (line 14). If no connections are available, getConnection
attempts to create another new connection (lines 15–16). It is possible
that numCons has decreased and a new connection can be created.
getConnection throws exceptions if neither a new (line 18) nor a free
(line 23) connection can be returned.

Database Access 4-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The releaseConnection Method


A connection pool client should call releaseConnection to return a
connection to the connection pool, once it is no longer needed. The
releaseConnection method is shown here.

1 public synchronized void releaseConnection(Connection con)


2 throws SQLException {
3
4 boolean reuseThisCon = reuseCons;
5
6 if (used.contains(con)) {
7 // Move this connection from the used list to the free list
8 used.removeElement(con);
9 numCons--;
10 } else {
11 throw new SQLException("Connection " + con + " did not
come from this ConnectionPool");
12 }
13 try {
14 if (reuseThisCon) {
15 free.addElement(con);
16 numCons++;
17 } else {
18 con.close();
19 }

4-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The releaseConnection Method (Continued)


20 // Wake up a thread waiting for a connection
21 notify();
22 } catch (SQLException e) {
23 /*
24 * The Connection seems to be broken, but it's off the used
list
25 * and the connection count has been decremented.
26 */
27 // Just to be sure
28 try {
29 con.close();
30 } catch (Exception e2) {
31 // We are expecting an SQLException here
32 }
33 notify();
34 }
35 }

The releaseConnection method is called by a connection pool client


to return a connection to the pool. This method checks to see if the
connection came from the pool (line 6) of used connections. If the
connection was in the used vector, it is removed (lines 8 and 9) and, if
possible (if the reuseThisCon flag is set to true), added back to the
list of available connections (lines 13–16). If reuseThisCon flag is set
to false, the connection is closed (lines 17–19, 22–34).

Note – Although not shown in the code fragment, the reuseThisCon


flag is set to true within ConnectionPool.

An exception is thrown if the connection was not found in the pool of


currently used connections (lines 10–11).

Database Access 4-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
The ConnectionPool API

The closeAll Method


A connection pool client should call closeAll to tear down the
connection pool. The closeAll method is shown here.

1 public synchronized void closeAll() {


2
3 // Close unallocated connections
4 Enumeration cons = ((Vector)free.clone()).elements();
5 while (cons.hasMoreElements()) {
6 Connection con = (Connection)cons.nextElement();
7
8 free.removeElement(con);
9 numCons--;
10
11 try {
12 con.close();
13 } catch (SQLException e) {
14 // The Connection appears to be broken anyway, so we will
ignore it
15 }
16 }
17
18 // Move allocated Connections to a list of Connections that are
closed
19 // when they are released.
20 cons = ((Vector)used.clone()).elements();
21 while (cons.hasMoreElements()) {
22 Connection con = (Connection)cons.nextElement();
23
24 used.removeElement(con);
25 }
26 }

The closeAll method closes all of the connections currently free (lines
4–12) and removes connections from the list used connections (lines
20–24). A connection is assumed broken if it cannot be closed (lines
13–14).
✓ It is not always necessary to call closeAll. A connection pool will be collected by the
garbage collector if a servlet or the Web server are unloaded. It is good practice to
perform your own tear down.

4-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Review of Database Access

Database access is fairly simple to implement using servlets.

● A database client has to accomplish the following to access a


database:

▼ Load the database driver (Class.forName )

▼ Establish a connection to the database


(DriverManager.getConnection)

▼ Create and execute a query (con.createStatement,


stmt.executeQuery)

▼ Parse and display the results (rs.getMetaData)

▼ Close the connection (con.close)

Database Access 4-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4

Review of Database Access

● A connection pool improves database access times by creating a


pool of reusable connections for use by a database client. A
connection pool client simply instantiates a connection pool and
calls its APIs to enable database access. Minimally, a connection
pool consists of:

▼ A constructor that creates the connection pool


(ConnectionPool). Generally, there are two pools of
connections: a pool of used connections and a pool of available
connections (used, free).
▼ A method to get a connection from the pool (getConnection).

▼ A method to return a connection to the pool


(releaseConnection).

▼ A method to tear down the entire pool of connections


(closeAll).

4-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Exercise: Enhancing a Database Servlet

Exercise objective – Modify a database servlet so that it uses a


connection manager and is thread safe.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

Database Access 4-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Exercise: Enhancing a Database Servlet

Tasks

Modifying DBServlet to Use a Connection Pool

The DBServlet performs queries to mydatabase, a database of


employee information. DBServlet uses println statements to create a
basic HTML form allowing end users to look up information for an
employee within the database. DBServlet does not use a connection
pool, instead, it creates and destroys connections on a per-request
basis. You must modify DBServlet to use the ConnectionPool.class
APIs and take advantage of the connection pool’s functionality.

1. From your home directory, change directory to mod4-jdbc/lab/.

2. Open the DBServlet.java file using text editor.

3. Modify DBServlet to:

▼ Load the iMsqlDriver. Use the following URL to connect to


the driver:
static final String url =
"jdbc:msql://database_hostname:1114/mydatabase";

Note – The database_hostname should be provided by your instructor.

▼ Instantiate or initialize a ConnectionPool. Examine the


ConnectionPool.java file to find the arguments passed to the
pool.

▼ Get a connection from the pool (getConnection).

▼ Send the query (the last name you fetch from the form) to the
database using the connection. The query string you will use is:

query = "SELECT first_name, last_name, comment" +


"WHERE last_name='"+ lname +"'";

4-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Exercise: Enhancing a Database Servlet

Tasks

Modifying DBServlet to Use a Connection Pool (Continued)

▼ Send the result of the query to dispResultsSet to be returned


to the browser. The dispResultsSet method is already
provided within DBServlet.

▼ Send the following items to the event_log:


● IP address of the client accessing the database
● Message indicating that a connection was retrieved from
the pool
● A message indicating that a connection was returned to the
pool
▼ Return the connection to the pool (releaseConnection).

▼ Close all of the connections upon termination.

▼ Accept the database URL and driver names as init parameters


(optional).
✓ Note that these items are currently static final. Students will have to alter these
modifiers to use these items as init parameters (remove the final modifier).

4. Save and compile your new DBServlet.java servlet.

5. Copy DBServlet.class and ConnectionPool.class to the


server_root/servlets directory.

6. Test DBServlet directly using a URL. You will not notice anything
different about DBServlet until you have multiple clients
(browsers) trying to access it at the same time. Access time should
be reduced when multiple clients access DBServlet at the same
time.

Note – The following last names are valid for testing DBServlet:
Smith, McNealy, Colorado, Cruz, and Presson.

Database Access 4-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Exercise: Enhancing a Database Servlet

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

4-38 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Identify the components of two-tier and multi-tier architectures

❑ List three distributed Java technology computing solutions

❑ List the four steps needed to create a simple database access client

❑ Identify the two considerations for designing Web-based database


solutions

❑ Identify the two types of connection lists needed in a connection


pool

❑ List the basic APIs necessary in a connection pool class

❑ Update the DBServlet to implement connection management,


quick database access, and thread safety

Database Access 4-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
4
Think Beyond

What are some additional database-related modifications that might be


added to a connection pool?

4-40 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
RMI and CORBA/IDL 5

Course Map
Servlets offer a gateway into an abundance of Java technologies such
as JDBC and remote method invocation (RMI). This module discusses
the use of RMI and CORBA/IDL technologies in conjunction with
servlets.
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

5-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following question is relevant in understanding the


topics presented in this module.

In what ways can RMI or CORBA/IDL be used within a servlet?

✓ A servlet can be an RMI or CORBA/IDL client or server.

✓ An RMI servlet can be used in a four-tier solution to fetch database fields.

5-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Objectives

Upon completion of this module, you should be able to

● Define the purpose of remote method invocation (RMI)

● Identify the four items for implementing a basic RMI server

● Identify the two items for implementing a basic RMI client

● Identify the six steps to install and invoke an RMI client and
server

● List two differences between RMI and CORBA/IDL

● Configure and invoke an example RMI servlet solution

References
Additional resources – The following reference can provide additional
details on the topics discussed in this module:

● Java IDL Documentation. [Online] Available:


http://java.sun.com/products/jdk/idl/docs.html)

RMI and CORBA/IDL 5-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

RMI

RMI enables programs written in Java programming language to


invoke objects in different virtual machines, potentially on different
host machines. These objects are called remote objects. An object of
this type is described by one or more remote interfaces, which are
interfaces for Java technology (“Java interfaces”) that declare the
methods of the remote object. So, more specifically, RMI is designed to
allow your programs to invoke method of a remote interface on a
remote object. The method invocation on the remote object has the
same syntax as a method invocation on a local object.

An RMI solution consists of RMI servers, clients, and the RMI registry.
An RMI server implements an RMI object interface and registers the
object with the RMI registry. The RMI registry is a daemon that keeps
track of all of the available remote objects. The RMI server must have
access to skeletons for the server class. A skeleton for a remote object is
a server-side entity that contains a method which dispatches calls to
the actual remote object implementation.

5-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI

An RMI client makes calls to an RMI registry to look up remote


objects. An RMI client must have access to a stub instance for the
server class. A stub is a client-side proxy for the remote object. Stubs
implement all of the interfaces that are supported by the remote object
implementation. Stubs and skeletons provide the communication
mechanism used by the client and server.

The Java RMI API provides a set of classes and methods that handle
the serialization of any object passed as an argument in a method
invocation. The API also takes care of all communication and
parameter referencing.

RMI and CORBA/IDL 5-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI Client, Server and Registry Interaction

Figure 5-1 shows the interaction among the RMI client, server, and
registry.

**Stub Remote object


implementation
4 5
9
6 7
RMI client
program 8 *Stub
*Skeleton
2 3
RMI Client JVM RMI server
program

1
RMI registry RMI Server JVM

**Stub

* Created as part of registration / export


RMI Registry JVM ** Serialized and shipped via networking

Figure 5-1 RMI Client, Server, and Registry Interaction

1. The RMI server program creates an instance of the remote object


implementation and passes a serialized form of its stub to the RMI
registry. The stub is registered with the RMI registry.

2. The RMI client program attempts to get a handle to the remote


object from the registry.

3. The RMI registry returns a serialized copy of the stub to the RMI
client program. The RMI client program deserializes the stub to
create an instance.

4. The RMI client program calls one of the remote object’s methods
via the stub instance.

5. The stub contacts the skeleton within the RMI server.

5-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI Client, Server, and Registry Interaction

6. The skeleton invokes the method on the implementation of the


remote object.

7. The remote object implementation’s method returns the result to


the skeleton.

8. The skeleton returns the result to the RMI client stub.

9. The RMI client stub returns the result to the RMI client program.

RMI and CORBA/IDL 5-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

Implementing a Basic RMI Server

Follow these steps to create RMI server components:

1. Create a remote interface for your object by extending


java.rmi.Remote.

2. Develop an implementation of the remote interface and extend


java.rmi.server.UnicastRemoteObject.
✓ The first two items are not part of the server program, but are necessary on the same
machine Java Virtual Machine (JVM) as the RMI server.

3. Instantiate the remote object.

4. Register the remote object stub with the RMI registry.

5-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

Implementing a Basic RMI Client

Follow these steps to create RMI client components:

1. Use the RMI Naming class to look up and instantiate the remote
object stub from the RMI registry.

2. Invoke the remote object’s methods.

RMI and CORBA/IDL 5-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

Installing and Invoking the Server, Client, and RMI Registry

Follow these steps to install and invoke the RMI client, server, and
registry:

1. Place the interface class on the server and client.

2. Place the implementation of the interface on the server.

3. Generate stubs and skeletons using the rmic compiler. Place the
stubs and skeletons on the server and the stubs on the client.

4. Put stubs on client and put skeletons on server.

5. Start the registry.

6. Start the server program.

7. Start the client program.

5-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

RMI and Servlets

A servlet can be an RMI server or client. You do not need to do


anything special to develop an RMI servlet client or server aside from
following the guidelines mentioned previously. An RMI servlet client
can access a server that is another servlet or application on the same
Web server, or remotely.

RMI and CORBA/IDL 5-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

RMI and Servlets

An Example RMI Servlet Solution


The following example demonstrates one way to incorporate Java RMI
technology into a servlet. This example uses a servlet as an RMI client
to a database object. This example is a multi-tier example whereby an
applet (ServletApplet) is used to access the RMI client
(ClientLogServlet) which uses RMI naming services to retrieve a stub
instance to the remote object (a database) from the RMI registry.

5-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Server


The example RMI server includes the following files: Database.java,
DatabaseImpl.java, and RMIServer. The stubs and skeletons
accompanying the server are generated automatically by the rmic
compiler. The RMI server follows the steps for an RMI server
implementation (previously outlined in this module).

Database.java

1 import java.net.*;
2 import java.util.*;
3 import java.rmi.*;
4
5 public interface Database extends Remote {
6 public void addClient(String ip_addr, Calendar date)
throws RemoteException;
7 public Vector getClientVisits(String ip_addr)
throws RemoteException;
8 public long getNumberOfVisitors() throws RemoteException;
9 public long getNumberOfClientVisits(String ip_addr)
throws RemoteException;
10 public void close() throws RemoteException;
11 }

Database.java is the remote interface to the database object.

RMI and CORBA/IDL 5-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Server

DatabaseImpl.java

1 import java.sql.*;
2 import java.rmi.*;
3 import java.rmi.server.*;
4 import java.util.*;
5 import java.net.*;
6 import java.util.Date;
7
8 public class DatabaseImpl extends UnicastRemoteObject implements
Database
9 {
10 private Connection connection;
11 private Statement statement;
12 private Date thedate;
13
14 public DatabaseImpl(String driverName, String url) throws
StartupException, RemoteException
15 {
16 try
17 {
18 // Let's set up our connection to the database using JDBC
19 setupDBConnection(driverName, url);
20 }
21 catch(Exception e)
22 {
23 throw new StartupException(new String("Had a problem
connecting to db: "+url));
24 }
25 }
26

5-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Server

DatabaseImpl.java

27
28 /**************************************************************
29 * setupDBConnection is used to:
30 * 1) install the JDBC driver for mSQL
31 * 2) establish a connection to the DB
32 * 3) create a statement allowing us to interact with the DB
33 ***************************************************************/
34 private void setupDBConnection(String driverName,
String url) throws Exception
35 {
36 ...
37 }
38
39 /*************************************************************
40 * addClient adds a record to the Client table of the DB.
41 * It converts the string to a String representation and
42 * the calendar to a string (because of the Mini-SQL limitations).
43 * Normally, business logic or rules would be placed in here.
44 **************************************************************/
45 public void addClient(String ip_addr, Calendar date)
throws RemoteException
46 {
47 ...
48 }
49
50 /****************************************************************
51 * getClientVisits returns a Vector of Strings, each of which
52 * represents a visit.
53 *****************************************************************/
54 public Vector getClientVisits(String ip_addr)
throws RemoteException
55 {
56 ...
57 }

RMI and CORBA/IDL 5-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Server

DatabaseImpl.java

58
59 /******************************************************************
60 * getNumberOfVisitors calculates the total number of visitors in
61 * the database.
62 *******************************************************************/
63 public long getNumberOfVisitors() throws RemoteException
64 {
65 ...
66 }
67
68 /******************************************************************
69 * getNumberOfClientVisits calculates the number of times a client
70 * with the given String interacted with our service.
71 *******************************************************************/
72 public long getNumberOfClientVisits(String ip_addr)
throws RemoteException
73 {
74 ...
75 }
76
77 public void close() throws RemoteException
78 {
79 ...
80 }
81 }

DatabaseImpl is the implementation of the remote object interface.


DatabaseImpl performs all of the operations requested by the client.
✓ Students can think of DatabaseImpl as the “core” of the server; it actually performs the
work requested by a client.

DatabaseImpl contains a constructor that sets up the database object


by loading the database driver, getting a connection, and creating a
statement (line 19).

5-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Server

RMIServer.java

1 import java.rmi.*;
2
3 class RMIServer {
4 private final static String driverName =
"com.imaginary.sql.msql.MsqlDriver";
5 private final static String url =
"jdbc:msql://fuggles:1114/ClientLog";
6
7 public static void main(String args[]) {
8 try {
9 Database database = new DatabaseImpl( driverName,
url );
10 Naming.rebind("ClientLog", database);
11 } catch(StartupException se) {
12 System.err.println("StartupException: "+se.getMessage());
13 } catch(Exception e)
14 {
15 System.err.println("An Error occurred during RMI Server
initialization.");
16 e.printStackTrace();
17 System.exit(0);
18 }
19 }
20 }

RMIServer must be executed on the server machine (or where the


registry exists). RMIServer creates a remote object called database
(line 9) from the remote object implementation and binds the remote
object stub to the registry (line 10). The RMI client can access the
remote object once the bind has completed.
✓ The rmiregistry program has to be loaded before running the RMIServer program. The
exercise leads students through the execution of this example.

RMI and CORBA/IDL 5-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Client

ClientLogServlet

The RMI client accesses the remote database object through the RMI
registry.
1 import java.io.*;
2 import java.util.*;
3 import java.rmi.*;
4 import javax.servlet.*;
5
6 public class ClientLogServlet extends GenericServlet
7 {
8 static
9 {
10 System.err.println("CLIENTLOGSERVLET CLASS LOADED");
11 }
12
13 private Database database;
14 private ServletContext context;
15 private final String rmiParam = "RMI_Registry_Server";
16 private final String remoteObjParam = "Remote_Object_Name";
17
18 private String rmiRegistry, remoteObjectName;
19
20 public void init(ServletConfig config) throws ServletException
21 {
22 super.init(config);
23 context = config.getServletContext();
24 context.log("init in ClientLogServlet called");
25
26 try
27 {
28 rmiRegistry = config.getInitParameter(rmiParam);
29 System.err.println("rmiRegistry: "+rmiRegistry);
30 remoteObjectName = config.getInitParameter(remoteObjParam);
31 System.err.println("remoteObjParam: "+remoteObjectName);
32

5-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Client

ClientLogServlet (Continued)

33 if(rmiRegistry != null && remoteObjectName != null) {


34 System.err.println("URL: " +
"rmi://" + rmiRegistry + "/" + remoteObjectName);
35 database = (Database)
Naming.lookup("rmi://" + rmiRegistry + "/"
+ remoteObjectName);
36 System.err.println("found registry");
37 } else {
38
39 log("InitParams were not specified... using default
values");
40 database = (Database)
Naming.lookup("rmi://localhost/ClientLog");
41 System.err.println("found default registry");
42 }
43 }
44 catch(Exception e)
45 {
46 System.err.println("Did NOT work");
47 e.printStackTrace(System.err);
48 context.log(e,"ERROR GETTING RMI REGISTRY");
49 destroy();
50 }
51 }
52
53 public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
54 {
55 try
56 {
57 context.log("service ClientLogServlet called");
58 System.err.println("Request class: "+req.getClass());
59 System.err.println("Response class: "+res.getClass());
60 ServletOutputStream resOut = res.getOutputStream();
61 System.err.println("got output stream");

RMI and CORBA/IDL 5-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Client

ClientLogServlet (Continued)

62 ObjectOutputStream oos = new


ObjectOutputStream(resOut);
63 System.err.println("got object output stream");
64 String clientInetAddr = req.getRemoteAddr();
65 System.err.println("got clientIntAddr: " + clientInetAddr);
66
67 database.addClient(clientInetAddr, Calendar.getInstance());
68 System.err.println("added client: ");
69 long totalVisitors = database.getNumberOfVisitors();
70 System.err.println("got totalVisitors: "
+ totalVisitors);
71 long clientVisits =
database.getNumberOfClientVisits(clientInetAddr);
72 System.err.println("got clientVisits: "+clientVisits);
73 Vector dates =
database.getClientVisits(clientInetAddr);
74
75 oos.writeLong(totalVisitors);
76 System.err.println("wrote totalVisitors");
77 oos.writeLong(clientVisits);
78 System.err.println("wrote clientVisits");
79 oos.writeObject(dates);
80 System.err.println("wrote dates");
81 }
82 catch(Exception e)
83 {
84 System.err.println("Problem in ClientLogServlet: ");
85 e.printStackTrace(System.err);
86 context.log(e,"ERROR IN CLIENT LOG SERVLET");
87 }
88 }
89
90 public void destroy()
91 {

5-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Client

ClientLogServlet (Continued)

92 try
93 {
94 database.close();
95 }
96 catch(Exception e)
97 {
98 System.exit(0);
99 }
100 }
101}

RMI and CORBA/IDL 5-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Client

ClientLogServlet

The init Method

ClientLogServlet downloads, via serialization, a configured instance


of the remote object’s stub by calling the Naming.lookup with a URL
(lines 35 and 40). This servlet expects host name (for the RMI registry)
and remote object name (the database name) to be passed in, by the
Web server, as initialization parameters. A default value
(localhost:ClientLog) is used if these parameters are not available
via the ServletConfig object.
✓ Note that the lookup must be cast to the appropriate type as in line 35.

The service Method

The servlet calls the remote objects methods, via the stub instance,
within the service method. ClientLogServlet calls
database.addClient (line 67) to add the client browser’s IP address
and current date/time to the remote object.

Then ClientLogServlet calls database.getNumberOfVisitors (line


69) to get the number of total visitors who have accessed the remote
database object. ClientLogServlet also calls
database.getNumberOfClientVisits to get the number of times a
particular client has accessed the remote object. Finally, getVisitors
is called to get a vector of dates and Internet Protocol (IP) address for
clients who have accessed the remote database object.

The number of clients, dates, and Internet Protocol addresses are then
returned to an applet called RMIApplet.

5-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Applet


The RMI applet is used to invoke ClientLogServlet and build a report.
1 import java.applet.*;
2 import java.awt.*;
3 import java.net.*;
4 import java.io.*;
5 import java.util.*;
6
7 public class RMIApplet extends Applet
8 {
9 static {
10 System.out.println("Loading class");
11 }
12
13 public RMIApplet() {
14 System.out.println("Constructing applet instance");
15 }
16
17 private String servletName;
18 private long clientAccess, totalAccess;
19 private Vector dates;
20 private TextArea report = new TextArea(5, 20);
21
22 public void init() {
23 add(new Label("RMIApplet"));
24
25 try {
26 servletName = getParameter("servlet");
27 System.out.println("Got Servlet Name" + servletName);
28
29 setSize(500,500);
30 URL documentBase = getDocumentBase();
31 System.out.println("Got Document Base"
+ documentBase);
32
33 URL servletAddress = new URL(documentBase,
servletName);
34 System.out.println("Got Servlet Address" + servletAddress);

RMI and CORBA/IDL 5-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Applet (Continued)


35 InputStream input = servletAddress.openStream();
36 System.out.println("Got InputStream" + input);
37
38 ObjectInputStream objectInput =
new ObjectInputStream(input);
39 System.out.println("Got ObjectInputStream" + objectInput);
40
41 totalAccess = objectInput.readLong();
42 System.out.println("Performed first Read"
+ totalAccess);
43
44 clientAccess = objectInput.readLong();
45 System.out.println("Performed second Read"
+ clientAccess);
46
47 dates = (Vector) objectInput.readObject();
48 System.out.println("Read Vector" + dates);
49
50 report = new TextArea(5,40);
51 add(report);
52 buildReport();
53 validate();
54 } catch(Exception e) {
55 System.err.println("EXCEPTION: "+e.toString());
56 }
57 }
✓ This example shows applet-to-servlet communication using an HTTP connection to a URL.
Applet-to-servlet communication can be used in many servlet solutions.

5-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
RMI and Servlets

An Example RMI Applet (Continued)


58 private void buildReport() {
59
60 report.setText("Thanks for accessing our web site!");
61 report.append("\nThe total number of visitors is: "
+ totalAccess);
62 report.append("\nYou have accessed this site "
+ clientAccess+" times");
63 report.append("\n\nDates accessed:");
64 for(int i=0;i<dates.size();i++) {
65 report.append("\n"+(String)dates.elementAt(i));
66 }
67 System.err.println("REPORT: \n\n\n"+report.getText());
68 }
69 }

RMIApplet invokes ClientLogServlet by opening an


objectInputStream (line 40) and then reading the servlet response
into that stream (lines 43, 46, and 49). The servlet’s response is placed
within a report and displayed by the applet (lines 59–69).

RMI and CORBA/IDL 5-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

Java IDL

Overview
The JavaIDL API is actually a Java technology approach to the CORBA
technology. CORBA is similar to RMI. Server capabilities are described
in a specification file: the IDL file.

Like RMI, Java interface definition language (IDL) enables you to


create distributed Web-enabled Java applications that can
transparently invoke operations on remote network services. Java IDL
uses the industry standard Object Management Group IDL and IIOP
(Internet Inter-Object Request Broker Protocol) defined by the Object
Management Group.

5-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Java IDL

Overview (Continued)
An object request broker is a concept similar to the RMI registry. ORBs
are an IDL runtime responsible for all of the mechanisms required to
find the object implementation for the request, to prepare the object
implementation to receive the request, and to communicate the data
making up the request. The Java interface that the client sees is
completely independent of where the object is located, the
programming language it is implemented in, or any other aspect
which is not reflected in the object’s interface.

Java IDL and Servlets


A servlet can be CORBA/IDL server or client. There are no special
requirements of a CORBA/IDL servlet.

Note – The mod5-rmiidl/examples/rmiexample directory contains


another example RMI servlet included with Java Web Server.

Comparing RMI and CORBA/IDL


Here are two items to note, in comparison to RMI, about CORBA/IDL:

● The binaries that are executed are not composed of byte codes and
are therefore not platform independent. In turn, RMI can actually
move class files transparently from one machine to another if
required.

● CORBA does not support moving objects from server to client.


However, you can invoke a CORBA object’s methods or receive
data structures (this is under review for newer versions of
CORBA).
✓ RMI: a Java-technology-to-Java-technology solution.

✓ CORBA: a Java to C, C++, Pascal solution

RMI and CORBA/IDL 5-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5

Review of Java RMI and IDL

RMI and CORBA/IDL provide remote object invocation through an


RMI registry and an object request broker, respectively.

● RMI applications consist of an RMI server, RMI client, and an RMI


registry.

▼ The RMI server consists of an interface definition for the


remote object, an implementation of the interface, code for
creating the remote object and registering the object with the
registry, and stubs and skeletons.

▼ The RMI client uses RMI naming services to get an instance of


the stub for the remote object. The stub provides the client with
access to the remote objects methods.

▼ The RMI registry is a database of all registered remote objects.

● CORBA/IDL provides similar functionality for remote object


invocation as RMI.

● As with RMI, CORBA/IDL can also be used in conjunction with


servlets.

5-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Exercise: Configuring and Invoking the RMI Example

Exercise objective – Configure and run the RMI/servlet example


used in the course materials.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

RMI and CORBA/IDL 5-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Exercise: Configuring and Invoking the RMI Example

Tasks

Configuring the RMI Servlet Solution

1. From your home directory, change directory to mod5-rmiidl/lab.

2. Open the RMIServer.java file using text editor.

3. Make the following changes to RMIServer.java:

▼ Modify the url variable to include the host_name of the


database server.

4. Recompile RMIServer.java.

5. Copy RMIApplet.html to server_root/public_html.

6. Copy RMIApplet.class to
server_root/public_html/applets.

7. Copy ClientLogServlet.class to server_root/servlets.

8. Copy Database.class to server_root/servlets.

9. Copy DatabaseImpl_Skel.class and


DatabaseImpl_Stub.class to server_root/servlets.

10. Copy StartupException.class to server_root/servlets.

11. Copy DatabaseImpl.class to server_root/servlets.

12. Copy RMIServer.class to server_root/servlets.

5-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Exercise: Configuring and Invoking the RMI Example

Tasks

Invoking the RMI Servlet Solution

1. Configure ClientLogServlet’s two init parameters within Java Web


Server. You should be able to determine the names of these
parameters by examining the ClientLogServlet code.
✓ The two init parameters are: RMI_Registry_Server (the sane as host_name) and
Remote_Object_Name (ClientLog).

2. Start the RMI registry:

rmiregistry &

3. Start RMIServer:

java RMIServer

4. Access RMIApplet.html using the appletviewer. For example:

appletviewer http://host_name:8080/RMIApplet.html

You should notice that several messages are printed within the
window where RMIServer was started. Additionally, the applet should
receive messages from the ClientLogServlet.
✓ Inform students that the RMIApplet may take a while (1–3 minutes) to load.

Note – You will have to exit and reload the RMIApplet via the
AppletViewer to increment the values within the remote object.

RMI and CORBA/IDL 5-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Exercise: Configuring and Invoking the RMI Example

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

5-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Define the purpose of remote method invocation (RMI)

❑ Identify the four items for implementing a basic RMI server

❑ Identify the two items for implementing a basic RMI client

❑ Identify the six steps to install and invoke an RMI client and
server

❑ List two differences between RMI and CORBA/IDL

❑ Configure and invoke an example RMI servlet solution

RMI and CORBA/IDL 5-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
5
Think Beyond

Are there any distributed technologies, in addition to JDBC, RMI, and


CORBA/IDL, that can be used in conjunction with servlets?

5-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Persistent State in HTTP Servlets 6

Course Map
Persistent state allows information to be kept over time, and shared
among a series of Web pages sent by one server to the same browser.
This is central to many shopping-type applications.
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

6-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


the topics presented in this module.

Is information preserved between successive HTTP transactions from


the same browser?

✓ No, not unless it is written to a log file or is facilitated through an extension that sits on
top of HTTP, such as servlets.

How do multiple Web pages share information? For example, how is a


list of items in an electronic shopping cart tracked over several Web
pages?
✓ HTTP provides for the preservation of login information, but nothing more. The
HttpSession concept, introduced in this module, addresses this problem.

6-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Objectives

Upon completion of this module, you should be able to

● Define the term session and describe how a session can be used to
overcome limitations imposed by the stateless HTTP protocol

● List two ways a session can be tied to a browser

● Describe the relative strengths of cookies and sessions

● Develop Web shopping servlets using sessions

● Develop Web shopping servlets using cookies (optional)

References
Additional resources – The following reference can provide additional
details on the topics discussed in this module:

● Java Web Server Session Tracking. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/session_track/
SessionTr.html.

Persistent State in HTTP Servlets 6-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Benefits and Limitations of Statelessness in the HTTP Protocol

HTTP transactions are made in isolation of one another—they do not


have a mechanism for keeping track of a request or request data sent
using a Web browser. Therefore, HTTP transactions are said to be
“stateless.”

A benefit of statelessness, to the overall reliability of the World Wide


Web, is that client browsers do not usually notice when a server goes
down and comes up quickly.
✓ Some students might find it useful if you relate this to the NFS™ protocols which do the
same, for the same reasons.

However, statelessness has its drawbacks. For example, it is difficult to


produce groups of pages that collect information from the user to form
a “big picture” of the user’s experience.
✓ Actually, some history is kept, such as a log of requests, but this is not generally available
for reuse by subsequent pages.

✓ Other benefits include better security without state and low system resource overhead.

✓ Other disadvantages include Web pages cannot share information and keep track of
visited pages.

6-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Demonstrating the Benefits of State

Suppose you have a Web site that has a Web page for authenticating
users and a Web page for accessing a corporate database.

The authentication page is used for user identification and


authentication to the Web site. The data from this page is sent to a
servlet that performs the actual authentication. Once users are
authenticated, they are presented with a database Web page.

Persistent State in HTTP Servlets 6-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Demonstrating the Benefits of State

The database page provides access to a corporate database. However,


database access is granted only if the user has been successfully
authenticated at the authentication page. Furthermore, the information
available from the database must be restricted according to the
privileges of the individual user. Therefore, the servlet that controls
access to the database must be able to access data from the
authentication servlet before it can allow proper access to the database.
The database servlet must have access to the following state-related
information:

● Was the user correctly authenticated?

● If the user was authenticated, what are the privileges of the user?

How can the database servlet gain access to this information? There
are three approaches: cookies, sessions, or both.

6-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Cookies

Cookies are a mechanism for storing a variable and its associated value
on the client. The server requests that a cookie value be set when a
Web page is accessed. The browser has the option of accepting or
rejecting the cookie. If the cookie is accepted, the value is set. The same
value can be read back by the server at a later time, such as during the
handling of a later page request.

Most modern browsers support cookies. However, the acceptance of


cookies is usually user configurable; a browser will allow cookies to be
accepted or rejected automatically, accepted or rejected through a
dialog box, or disabled. These configuration options stem from
security concerns that have arisen from bugs in the implementations of
cookies on some browsers.

Persistent State in HTTP Servlets 6-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Cookies

Programming With Cookies


Using cookies within a servlet is simple. Among several methods, the
servlet API enables you to set a cookie and get a cookie for a browser.

Note – Sessions should be used in preference to cookies for all new


development.

6-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Cookies

Setting a Cookie
Follow these steps to set a cookie in a browser:

1. Create the cookie, giving it a name and initial value, both of


which should be text strings. For example:
Cookie c = new Cookie("MyName", "MyValue");

2. Set the cookie with the HttpServletResponse object, using the


addCookie(Cookie) method. For example:
resp.addCookie(c);

Note – The addCookie method must be called even if the cookie was
retrieved from the browser. If this is not done the cookie value will not
be set or modified in the browser.

Persistent State in HTTP Servlets 6-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Cookies

Retrieving a Cookie
The following code fragment shows how to retrieve a cookie:
1 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
2 Cookie [] allCookies = req.getCookies();
3 Hashtable cookieTable = new Hashtable();
4
5 for (int i = 0; i < allCookies.length; i++) {
6 cookieTable.put(allCookies[i].getName(), allCookies[i]);
7 }
8 }

HttpServletRequest’s getCookies method is used to read the value


of a cookie that is already set in the browser. This method returns an
array of all cookies that relate to this server (line 2). It is up to the
servlet to isolate an individual cookie before reading its value. Cookies
are isolated by putting cookie names into a hash table (line 6).

Note – The Hashtable is created as a convenience for looking up


individual cookie values; it is not a requirement of using the
getCookies method.

✓ Once you have created a cookie you can manipulate its contents using the methods in the
cookie class (such as setComment, setDomain, and setPath).

6-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

Conceptually, a session refers to a collection of related HTTP


transactions made by one browser to one server. As related to servlets,
a session is a collection of data associated with those transactions,
which is made available to servlets invoked by the browser. Session
data from an earlier HTTP transaction can be retrieved and used
during later transactions. This is particularly valuable in the situations
that require user authentication (login) or for collecting information for
a user who is traversing several Web pages. Using the previous
example, the login servlet can store authentication information in a
session to be used by the database access servlet.

Sessions are supported by the servlet APIs using an interface called


javax.servlet.http.HttpSession.
✓ JRun supports sessions.

✓ Sessions work much like a hash table where the name is the hashcode and the value is
the entry.

Persistent State in HTTP Servlets 6-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

The HttpSession Interface


Sessions are implemented through the
javax.servlet.http.HttpSession interface. A Web server
developer must provide a concrete class that implements this interface.
However, all programming will be done using the interface rather than
the implementation class.

The HttpSession interface provide two methods: getValue and


putValue. These APIs provide functionality similar to the Hashtable
class: A session acts as a collection of key/value pairs, where the key is
a String and the value can be any Object. Therefore, a session can
store and access information of any kind.

6-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

Example
This example demonstrates the use and programming of a session and
consists of two servlets:

● The login servlet

● The secret servlet

Persistent State in HTTP Servlets 6-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

Example

The Login Servlet

The login servlet will collect a user name and password from an HTTP
POST request. The POST request will be created using a simple HTML
form, although the design of the servlet does not preclude the use of
an applet. The user data will be validated, and if deemed accurate, an
HttpSession, containing the user name, password, and secret
information, is created and initialized.

The login servlet has an init and a doPost method. The init
method reads data from a configuration file. This file contains records
of user name, password, and secret information, separated by colons.
✓ There are many enhancements that could be made to this example. Ask students to
suggest enhancements. Indicate how they would implement these enhancements. Some
ideas are ability to manipulate, extend, and update the information within the session, or
the ability to log out. Note that logging out is possible by either deleting the login
information, or by destroying the session itself (via the invalidate method).

6-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Login Servlet : init Method

1 public void init(ServletConfig conf) throws ServletException {


2 String initFileName =conf.getInitParameter("InitFile");
3 try {
4 BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(
initFileName)));
5 String line;
6 while ((line = in.readLine()) != null) {
7 try {
8 StringTokenizer tok = new StringTokenizer(
line, ":");
9 String uName = (String)(tok.nextElement());
10 String pWord = (String)(tok.nextElement());
11 String persData = (String)(tok.nextElement());
12 String [] value = {pWord, persData};
13 database.put(uName, value);
14 } catch (NoSuchElementException ex) {
15 break; // abandon parsing this line and try the
next one
16 }
17 }
18 } catch (IOException e) {
19 throw new UnavailableException(this,
"IO troubles with startup");
20 }
21

The init routine parses input lines from the file specified by
InitFile (lines 2, 6, 8–11), loads an array called value with the
password and extra data (line 12), and loads a hash table called
database with the user name (line 13).

Persistent State in HTTP Servlets 6-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Login Servlet: doPost Method

Calls to the login servlet are serviced by the doPost method once the
servlet is initialized.
1 public void doPost(HttpServletRequest req,
HttpServletResponse resp) {
2 Hashtable reqParams = null;
3 try {
4 ServletInputStream sins = req.getInputStream();
5 reqParams = HttpUtils.parsePostData(
sins.available(),sins);
6 } catch (IOException e) {
7 ;
8 // trouble with the input stream. The empty
9 // hashtable will cause a suitable handling.
10 }
11 }
12 String user = ((String[])(reqParams.get("USER")))[0];
13 String pass = ((String [])(reqParams.get("PASSWORD")))[0];
14
15 Object entry;
16 String response = null;
17
18 if ((user != null) && (pass != null) && ((entry =
database.get(user)) != null)) {
19 String [] entryStrings = (String [])entry;
20 if (!pass.equals(entryStrings[0])) {
21 response = "Bad Password, access denied";
22 }
23 else {
24 response = "Welcome " + user;
25 HttpSession session = req.getSession(true);
26 session.putValue("loginservlet.user", user);
27 session.putValue("loginservlet.password", pass);
28 session.putValue("loginservlet.secrets",
29 entryStrings[1]);
30 }

6-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Login Servlet: doPost Method

31 }
32
33 else {
34 response = user + " is not a known user here";
35 }
36
37 resp.setContentType("text/html");
38
39 try {
40 Writer output = resp.getWriter();
41 output.write("<HTML>\n<BODY>\n" + response
+ "</BODY>\n<HTML>\n");
42 output.flush();
43 } catch (IOException ex) {
44 ex.printStackTrace();
45 }

First, the POST parameters are collected into a hash table. The hash
table is generated using the utility method parsePostData in the
HttpUtils class (line 5).

Next, the user name and password parameters are fetched from the
hash table (lines 12–13). If neither the user name nor the password is
null, the servlet’s main database is checked for a match on the
supplied user name. If a match is found, the corresponding data will
contain the password and secrets for the user (line 20). A final check is
made to determine if the password is correct. If the password is
correct, an HttpSession object is created and initialized with the
user’s user name, password, and secret data (lines 25–28).

Persistent State in HTTP Servlets 6-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Login Servlet: doPost Method

The bulk of the login servlet’s work is completed within this service
method. This code segment produces a session object for a valid login
attempt, or creates an error string for an invalid login. Any servlets
invoked by the same browser that invoked the login servlet can obtain
this session and manipulate the data in it.

Finally, the servlet returns a response to the browser that originated


the request. This response consists primarily of the message that has
been collected in the response variable and is properly formatted as an
HTML page (line 41).

6-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

Example

The Secret Servlet

The secret servlet checks for the existence of the session. The servlet
returns an error report if a session is not found. If the session is found,
the user information within the session is used to generate a dynamic
Web page containing secret information.

The secret servlet responds to a GET request with an HTML page


containing the secret information that was placed into the session by
the login servlet.
✓ Students may ask about the life of a session. Sessions expire if left unused for too long.
This is discussed in detail later in this module.

Persistent State in HTTP Servlets 6-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Secret Servlet: doGet Method

1 public void doGet(HttpServletRequest req,


HttpServletResponse resp) {
2 String response = "";
3 HttpSession session = req.getSession(false);
4 if (session == null) {
5 response = "Please log in before trying to use this
facility";
6 }
7 else {
8 String user = (String)(
session.getValue("loginservlet.user"));
9 String pass = (String)(
session.getValue("loginservlet.password"));
10 String secret = (String)(
session.getValue("loginservlet.secrets"));
11 response = "OK " + user + " your password was " + pass
+ " and your secret is " + secret;
12 }
13 resp.setContentType("text/html");
14
15 try {
16 Writer output = resp.getWriter();
17 output.write("<HTML>\n<BODY>\n" + response
+ "</BODY>\n<HTML>\n");
18 output.flush();
19 } catch (IOException ex) {
20 ex.printStackTrace();
21 }

First, the secret servlet checks to see if the session exists. To check for
the session, an argument of false is passed to the getSession
method (line 3). This method/argument combination requests that a
new session not be created if it does not already exist. If the session
does not exist, it is assumed that the login servlet has not yet been
executed properly, and therefore, the secret servlet issues a message
encouraging users to log in (lines 4–5).

6-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Example

The Secret Servlet: doGet Method (Continued)

The login is assumed to have completed successfully if the session is


found. The session object’s getValue method is used to extract the
values from the session (lines 8–10). These values are used to create a
response message which is sent back as an HTML page once it has
been prepared (lines 16–17).

Persistent State in HTTP Servlets 6-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Sessions

Additional Guidelines
There are several additional guidelines for working with sessions.
These guidelines are:

● A session is not created for a browser automatically. A servlet


must create a session.

● A servlet can determine if a session already exists through one of


the following mechanisms:

▼ Use getSession(false) and check for a null return.

▼ Use getSession(true) and call isNew on the resulting


session.

You should check the integrity of the session’s data regardless of


the mechanism you use. Checking session data integrity is
important because the session might have been created by an
entirely unrelated servlet.

6-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Sessions

Additional Guidelines
● Any servlet can request that a session be created. However, if a
session already exists for the browser, it will be reused.

● The information within a session is available to all servlets


handling the target browser. Be careful when naming session
entries, otherwise ambiguity might arise. For example, a session
entry called reasonCode might be used by a job application
servlet to indicate why the applicant left a previous job. This same
entry could also be used by a sales enquiry servlet to indicate the
reason for a customer discount. When both servlets are used by
the same browser, reasonCode loses its significance. Therefore, it
is a good idea to use dotted style hierarchical names, such as
JobApplication.reasonCode
and“SalesEnquiry.discount.reasonCode for similar session
entries in related servlets.

● Sessions can be invalidated and therefore become unusable, either


by timing out, or by a servlet calling the invalidate method. A
servlet should not call the invalidate method because servlets do
not have a mechanism for determining if any other servlets are
using the same session. The best way to destroy a session is by
enforcing a timeout.

● A session can time out and become invalid due to browser


inactivity. The global session.invalidation property can be
modified to indicate new timeout values. The
session.invalidate property defaults to 30 minutes. Other
mechanisms, aside from sessions, should be used to store
persistent data that must be stored for longer periods since this
property is not under the control of individual servlets that might
be using the session.

Persistent State in HTTP Servlets 6-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Tying a Session to a Browser

Cookies
A Web server can use two ways to track the session that relates to a
browser. The simplest and most effective approach is to have the
server set a cookie in the browser.

However, as mentioned previously, some browsers do not support


cookies and users often do not allow their browsers to receive cookies
due to security reasons. An alternative mechanism, called URL
rewriting, can be used to keep track of the session.

6-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Tying a Session to a Browser

URL Rewriting
URL rewriting allows a session to be tied to a browser by adding a
session ID to a requested URL. The Web server recognizes this extra ID
information and extracts it from the URL when the browser attempts
to follow a link. The restored URL (without the ID) is used to load the
page, while the ID is used to track the session. For example, if the
current session ID is DA32242SSGE2 and the URL /store/catalog is
requested, the rewritten URL would be:
/store/catalog;$sessionid$DA32242SSGE2

URL rewriting is cumbersome, as all local URLs sent to the client must
be modified. Each HTML page must be scanned by the server to
determine all the data that gets sent to the client.

The page-scanning process is time consuming. However, this process


becomes more efficient if a servlet is issuing output to a browser.
Rewriting, within a servlet, is done by means of two special
HttpServletResponse methods: encodeURL and
encodeRedirectURL.
✓ Students might ask why the browser’s Internet address is not sufficient to determine the
session. This is a reasonable question from students who use machines in a single-user
mode. Those students who use multi-user systems with multiple users logged in
simultaneously will be able to explain the answer to this question. Some might suggest
that the port number of the request would be sufficient to identify a single browser in a
multi-user environment, but this is not the case since each HTTP transaction is separate,
and may use a distinct (random) source port number.

● A session can be lost when servlets fail to make the proper


encodeURL calls or if the user moves to a Web page located on a
different server. Therefore, it is important that all servlets use the
URL rewriting methods even if the servlets themselves are not
intended for use in a cookieless environment.

Persistent State in HTTP Servlets 6-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Cookies and Sessions Compared

There are several of issues that should be considered when choosing to


implement cookies or sessions in your servlets.

● Cookies are often disabled by Web browser users due to perceived


security risks. While this prevents cookies from operating, the
session mechanism has its own mechanism, called URL rewriting,
for handling persistent state.

● Cookies can store only one piece of information at a time, while a


single session can contain many pieces of information, related or
not. Multiple cookies can be used to store multiple data items.
However, if users have set the security options on their browsers
to warn when a cookie is set, they will receive multiple warnings,
which may be irritating.

● There are various versions of the cookie specification. Commonly,


all cookies accept text. However, even text characters can cause
problems.

6-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Cookies and Sessions Compared

● Cookie space may be limited in the client. Typical limits are 20


cookies per client, each cookie occupying 4 Kbytes of memory.
Although 4 Kbytes per cookie might seem a lot, keep in mind that
large cookies waste bandwidth each time they are sent in an HTTP
request header (especially if they are not used). By contrast, the
session mechanism places memory load only on the server, and
adds almost nothing to the bandwidth requirements between
browser and server.

Sessions and cookies are both supported by the servlet APIs.


However, as most of the previous points indicate, it is preferable to use
sessions, rather than cookies, in your servlets.

● In some instances you might use cookies. For example, you might
use cookies when writing a servlet that will interact with other
pre-existing Web pages that use cookies, such as those created by
standard CGI scripts.
✓ The following table can be written on the board to convey the differences between cookies
and sessions:

✓ Cookies ✓ Sessions

✓ Memory size limit of 2k. ✓ Memory limit depends on


server memory.

✓ Multiple cookies (1 ✓ Single session for as


name=value pair per much information as
cookie) needed.

✓ Number of cookies on ✓ Number of sessions


client is limited. depends on server
memory.
✓ Contains text only. ✓ Contains Java technology
objects.

Persistent State in HTTP Servlets 6-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Review of Cookies and Sessions

Cookies and sessions can be used to keep track of information during


the course of interaction between a particular browser and a particular
Web server.

● Cookies are a mechanism for storing a variable and its associated


value in the browser.

● Cookies can be configured, within a browser, to be accepted


automatically, accepted using a user dialog, or rejected.

● Not all browsers support cookies.

● Cookies are accessible using the servlet API’s


response.addCookie and request.getCookie methods.

6-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6

Review of Cookies and Sessions

● A session is a collection of data associated with transactions made


between a browser and a Web server.

● A session must be created by a servlet before it is accessible.

● To obtain a reference to a pre-existing session object, issue the call


HttpSession existingSession = req.getSession(false);
● Call getSession(true) if you want the session to be created after
attempting to get a session that does not already exist:
HttpSession possiblyNewSession =
req.getSession(true);
● Use putValue(key, value), where key is a String and value is
any object, to store information in the session object.
session.putValue(key, value);

Persistent State in HTTP Servlets 6-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Review of Cookies and Sessions

● Use getValue(key), where key is a String and value is any


object, to retrieve information from the session object.
value = session.getValue(key);
● URL rewriting should be used to track a session to a browser, as
cookies may not be available.

● Use encodeURL and encodeRedirectURL to attach a sessionID to


the URLs generated by your servlets.

6-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Exercise objective – Create two servlets: a login servlet (ShopLogin)


and a purchase servlet (ShopBuy). Each servlet will collaborate to use
sessions.

Note – These exercises are presented using sessions. However, sample


solutions for the servlets in this exercise (ShopLogin and ShopBuy) are
provided using cookies (ShopCookieLogin and ShopCookieBuy). If
you are currently implementing cookies on your Web server, you can
complete the exercises using cookies. However, you should use
sessions for all of your new state-related programming.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

Persistent State in HTTP Servlets 6-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopLogin Servlet

The ShopLogin servlet is derived from the example used in this


module. ShopLogin allows users to authenticate to a Web shopping
server and gain access to an electronic shopping cart.

1. From your home directory, change directory to mod6-


session/lab/.

2. Copy the file Login.java, which is taken from the module


example, to a new file called ShopLogin.java.

3. Copy the configuration file test.dat to a new file called


ShopUsers.txt.

4. Edit ShopUsers.txt.

ShopUsers.txt will contain two user name/password account


combinations (Fred:secret and Rich:obvious). Add the
following to each account:

▼ A credit limit to each user account

5. Save and exit ShopUsers.txt.

6. Open ShopLogin.java using text editor.

7. Add or modify the following in ShopLogin.java.

▼ Change the class name to ShopLogin.

▼ Change the third field of the session to represent a credit limit


rather than “secrets.”

▼ Ensure that an unsuccessful login causes a “rejection page” to


be sent as a response. The rejection page should contain a link
to the initial login page (ShopLogin.html).

▼ Ensure that a successful login causes a “welcome” page to be


sent as a response. The welcome page should print the credit
limit and contain a link to the purchase page (ShopBuy.html).

6-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopLogin Servlet (Continued)

8. Save the ShopLogin.java file after you have made changes.

9. Generate a ShopLogin.class file.

10. Copy the ShopLogin servlet and ShopUsers.txt file to


server_root/servlets.

11. Copy the ShopLogin.html file to server_root/public_html.

12. Configure the ShopLogin servlet. Remember to configure the


InitFile initialization parameter using Java Web Server’s
properties editor. The property should be set to InitFile and
the value should be set to servlets/ShopUsers.txt.

13. Test ShopLogin by invoking the ShopLogin.html Web page.

Note – Consider how you would support URL rewriting in the


ShopLogin servlet that you create. The solutions directory contains a
ShopLogin that implements URL rewriting.

✓ Note–Embedding hard-coded URLs into a dynamically generated page might create


confusion for a Web site administrator if the administrator is unfamiliar with dynamic
HTML and/or needs to reorganize the Web server layout.

✓ Suggest the use of an initParameter to allow the servlet to be reconfigured.

✓ Embedded URLs should be subjected to the encodeURL method to avoid issues with
cookieless browsers [URL Rewriting].

Persistent State in HTTP Servlets 6-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopBuy Servlet

The ShopBuy servlet allows a user to purchase products from a pull-


down menu. A response is returned, after each product is selected,
showing the items in the shopping cart. This servlet demonstrates how
to share a session between two servlets.

1. From your home directory, change directory to mod6-


session/lab/.

2. Create a purchase servlet called ShopBuy. ShopBuy should:

▼ Ensure that users are authenticated before attempting to


access this servlet. If users are not authenticated, they should
receive a response with a link pointing back to ShopLogin
servlet.
▼ Get the session used by ShopLogin.

▼ Check the session for a shopping list object and create a


shopping list object if it does not exist (session.getValue).
✓ Students could use a Vector as a member of the session for the shopping list. A Vector
would allow for an arbitrary number of items. An array could be used to minimize compute
load on the server, but is not as adept at handling variable length.

▼ Parse the PURCHASE parameter, sent by the ShopBuy.html


form, for the product that is to be purchased. ShopBuy.html
is provided in the mod6-session/lab/ directory.

▼ Put the name of the product into the shopping list


(session.PutValue).

▼ Return a response for each purchase selected. The response


should contain all of the current items in the shopping list.

6-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopBuy Servlet (Continued)

3. Save the ShopBuy.java file after you have made changes.

4. Generate a ShopBuy.class file.

5. Copy the ShopBuy servlet to server_root/servlets.

6. Copy the ShopBuy.html file to server_root/public_html.

7. Test ShopBuy and ShopLogin by invoking the ShopLogin.html


Web page.

Persistent State in HTTP Servlets 6-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopBuy Servlet (Continued)

8. ShopBuy.html demonstrates the beginnings of a full Web


shopping solution. What type of functionality could you add to
ShopBuy.html and the ShopBuy servlet?
✓ The page could have an attractive user interface, present price information for each
product, allow the user to select more than one product at a time, present the user with a
running total of cost of goods ordered, present the user with a credit remaining, allow
users to remove items from the shopping list, allow users to provide customer information
(including shipping and method of payment), and allow users to commit a purchase via
electronic commerce.

✓ It might be best to provide an applet to deliver the purchase interface, and have that
communicate directly with the shopping servlet. Do not forget that an applet can be more
responsive to user input, and require less HTTP traffic for a complex page display.

✓ Students may want to implementing a log-out feature. It is generally worth considering the
consequences of leaving information in a session “forever.” While the session will be
destroyed eventually, the data in it that represents a secret login should be timed out
sooner or deliberately removed. Otherwise, there is a possibility that the browser might be
left unattended and misused by some unauthorized person.

9. (Optional) The mod6-session/solutions/ directory contains a


ShopManage servlet that handles the removal of items from the
shopping list (a feature of most Web shopping solutions).
ShopManage also allows a user to “commit” to a transaction. You
can

▼ Copy ShopManage.class to server_root/servlets.

▼ Copy ShopManage.html to server_root/public_html.

▼ Test ShopManage by invoking the ShopManage.html Web


page.

10. (Optional) Incorporate the UNBUY and COMMIT features of


ShopManage into the ShopBuy servlet.

6-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Tasks

Creating and Invoking a ShopBuy Servlet (Continued)

11. (Optional) Provide a mechanism to determine price and available


quantity for each product. Use this mechanism to keep a running
total of purchases and an account balance based on the credit
limit.
✓ In a true Web shopping system, applications would need access, probably via a singleton
type mechanism, to a database of product including quantities on hand and prices.
Pricing and quantity information would be incorporated into the Web shopping page. Most
likely the list of products in the database would grow dynamically, which suggests that a
servlet should be written to dynamically query the database and produce a page of items.
Advanced students might want to attempt this if they complete the exercises.

Persistent State in HTTP Servlets 6-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Exercise: Developing a Web Shopping Solution

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

6-38 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish the following:

❑ Define the term session and describe how a session can be used to
overcome limitations imposed by the stateless HTTP protocol

❑ List the two ways a session can be tied to a browser

❑ Describe the relative strengths of cookies and sessions

❑ Develop Web shopping servlets using sessions

❑ Develop Web shopping servlets using cookies (optional)

Persistent State in HTTP Servlets 6-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
6
Think Beyond

Can you identify security implications in having browsers “log in” to a


server?

How might a browser be notified of any new products without having


to query the Web shopping server?

6-40 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Time-Extended Connections 7

Course Map
A servlet may need to pass information to a browser on a continuous
basis. This functionality requires a special “time-extended” connection.

Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

7-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


the topics presented in this module.

What happens if data in a Web page changes after the browser has
downloaded the Web page?

✓ Nothing. Web pages are static and the information viewed by the user becomes silently
out of date unless the user manually reloads the page. Even if the page is reloaded,
information may still be out of date, as caching proxies might fail to fetch the updated
information.

Can you think of situations where Web pages might need to be


updated regularly? Is it sufficient for the user to click the Reload
button on the browser, to update a page at intervals?
✓ These situations involve monitoring live or asynchronously updated data, such as stock
prices, control system temperature/pressure/velocity monitoring, chat systems, email
clients, even video images. Another example is National Aeronautics and Space
Administration’s (NASA) flight telemetry monitoring system used for the Hubble space
telescope and other vehicles. If any of the students attended the second JavaOne™ in
1997, they will have seen this.

✓ Presumably students will agree that clicking the Reload button at intervals is not good
enough for most serious applications.

7-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Objectives

Upon completion of this module, you should be able to

● Define the term time-extended connection

● Identify the difference between client-side pull and server-side


push

● List four options for maintaining a time-extended connection and


outline the strengths and/or weaknesses of each

● Develop a user datagram protocol (UDP) transaction monitor


servlet

References
Additional resources – The following default reference can provide
additional details on the topics discussed in this module:

● Appendix D, “Java Socket Programming,” which describes


Transmission Control Protocol/Internet Protocol (TCP/IP)
addressing and the use of sockets in the Java programming
language to perform UDP, broadcast, and multicast connectivity.

Time-Extended Connections 7-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

What Is a Time-Extended Connection?

The normal HTTP transfer mechanism is designed to send static pages


over the Web. Information is updated only when the user requests a
new page.

However, there are situations when a Web page should be updated


automatically (without user intervention) such as in a transaction
processing system. These situations require a special connection called
a time-extended connection. A time-extended connection is a mechanism
which enables new data to be sent to the client, automatically, at
regular intervals.
✓ This module is a survey of time-extended connection options. It was designed to get
students thinking about these options and to investigate further on their own time. The
lab covers one particular option.

7-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

Implementation Options

There are many different ways that a time-extended connection can be


implemented. Unfortunately, there is no single correct approach. Each
implementation option contains several advantages and
disadvantages.

Client Pull and Server Push


Ongoing updates to a client can happen in one of two ways; either the
client makes regular requests for updates, or the server sends new
data as it becomes available.

Implementation options which require the client to make update


requests is called client pull. Conversely, options which require the
server to send data are called server push.

Time-Extended Connections 7-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Implementation Options

Efficiency of Client Pull and Server Push


A client using client pull must establish a polling rate: an interval
representing when the client should pull information from the Web
server. Polling rates can be ineffective. If the client makes a request
every 20 seconds, then the displayed data might be 20 seconds out of
date. However, if the client requests occur four times a second, the
bandwidth demands on the network will too high. This could be
especially inefficient if the server is trying to support thousands of
clients (some of which could be polling for data that hasn’t necessarily
changed).

Server push is more efficient than client pull because network transfers
and central processing unit (CPU) usage only occur when new data is
available. A Web server must keep track of all the interested parties in
a server push option.

The implementation options described in this module are either server


push or client pull. These options are:

● HTML and dynamic updates

● Java technology and dynamic updates

▼ Continuous or transient TCP connections

▼ User datagram protocol (UDP)

▼ Broadcast and multicast connections

7-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

HTML and Dynamic Updates

Some of the widely supported proprietary HTML extensions can be


used to implement either a client pull or server push solution. For
example, JavaScript™ enables a Web page to automatically display a
new page after a predetermined period of time. Other extensions
provide similar solutions.

For example, it is possible to cause an HTTP connection to remain


open for an extended period of time. The Web server would send new
data to this connection as updates become available. While this might
work for short periods of time, some Web browsers can actually force
this type of connection to time out after an extended period of time
(usually 10 minutes).

Time-Extended Connections 7-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

Java Technology and Dynamic Updates

The Java programming language offers several additional solutions for


time-extended connections. For example, a client pull solution can be
implemented within an applet. The applet can spawn a new thread in
which a new connection is made at intervals and new data is
downloaded.
✓ Applets cannot do server push unless the applet opens a socket to the Web server.

7-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

Continuous or Transient TCP Connections

Transmission control protocol (TCP) is a connection-oriented


transmission protocol; for reliability, TCP requires a connection before
a message can be sent. The TCP connection is established by creating a
unique server and client socket to be used for the duration of a point-
to-point conversation.

A TCP connection can be used as a time-extended connection. In a


time-extended situation, client and server sockets would exist until
they were no longer needed by the client. Remember, a unique server
socket will be created for each client wanting to communicate with the
server. Therefore, using TCP as a time-extended connections option
can cause a large number of connections to be created on the Web
server, each utilizing server resources for an extended period of time.

Note – It is also wasteful, relative to CPU time and network


bandwidth, if a connection is created (and destroyed) for a single short
transaction.

Time-Extended Connections 7-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Continuous or Transient TCP Connections

✓ One of the possible approaches for a transient connection would be to have the client
create a server socket, and have the server connect to that when new data will be sent.
This, unfortunately, is not possible in an applet environment since the security model for
applets generally disallows the creation of server sockets by applets.

Note – Refer to Appendix D, “Java Socket Programming,” for


additional information on TCP communication using the Java
programming language.

7-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

User Datagram Protocol

User datagram protocol (UDP) is a transmission protocol that does not


involve setting up a connection before sending a message. In addition,
UDP does not require a separate connection at the server for each
client. Simply put, UDP solves the scalability issues of TCP.

Unfortunately, UDP is not reliable: there is no way of ensuring that a


UDP message, commonly called a datagram, is delivered. In fact, unlike
TCP, UDP messages may not reach their destination or may be
received in a different order from that in which they were sent.

Time-Extended Connections 7-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
User Datagram Protocol

Despite these limitations, UDP is still a valuable communication


mechanism. Missing an update from time to time might not matter,
especially if updates are frequent. Additionally, it is possible to design
a mechanism allowing the receiver of a message to determine if it has
missed any messages and to request that lost messages be resent.
✓ This is usually achieved by adding a sequence number to the transmissions; if you see
packets 4, 5, and 7, then you know you have missed number 6.

Note – Refer to Appendix D, “Java Socket Programming,” for


additional information on UDP communication using the Java
programming language.

7-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

Broadcast and Multicast Connections

Because UDP is not connection oriented and does not require


confirmation or failure responses, UDP allows datagrams to be sent to
multiple recipients.

Handling multiple recipients can be accomplished using one of two


options.

● A broadcast message is sent to a special IP address. Clients can


choose to receive all messages sent to this address. Generally,
broadcast packets cannot pass through routers and therefore are
inappropriate for communication on the Internet. However, it is
possible to configure an intranet to work with broadcast.

Time-Extended Connections 7-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Broadcast and Multicast UDP

● A multicast message is sent to a special group IP address. Clients


can then “join” the special address and receive all messages sent to
the address. Multicast has a set of special protocols that allow it to
work over the Internet. However, some popular systems do not
support multicast at all.
✓ The Windows 95 and Windows 98 TCP stacks do not support multicast; Windows NT does.

Note – Refer to Appendix D, “Java Socket Programming,” for


additional information on UDP broadcast and multicast
communication using the Java programming language.

7-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7

Review of Time-Extended Connections

A time-extended connection is useful when sending information, on a


continuous basis, between a client and a server. Here are several
important items to remember about time-extended connections:

● Time-extended connections are either client pull or server push.

▼ Client pull refers to a client pulling information from a server


at a defined interval.
▼ Server push refers to a server sending information to a client
when information has been updated.

▼ Client pull connections are inefficient because there is no way


to ensure that the information that is pulled is new.

Time-Extended Connections 7-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Review of Time-Extended Connections

● Four time-extended implementation options are discussed in this


module:

▼ Dynamic updates using HTML: You can use HTML extensions


to implement client pull and server push solutions. However,
some Web servers will cause this type of connection to time-
out.
▼ Continuous or transient TCP connections: You can use TCP to
send data reliably, but server resources are heavily utilized
because a separate connection is maintained on the server for
each client.

▼ User datagram protocol: You can use UDP to send data


unreliably. Reliability can be built in by checking datagram
order and ensuring data integrity.

▼ Broadcast or multicast connections: You can use UDP broadcast


or multicast to push information to several clients at once.
Multicast is more efficient because it only sends messages to a
list of clients and messages can travel across routers.

7-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a Transaction Monitor

Exercise objective – This exercise is an extension to the shopping


servlets you worked with in Module 6, “Persistent State in HTTP
Servlets.” You will use a time-extended connection to monitor activity
in the shopping server.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

Time-Extended Connections 7-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a UDP Broadcast Transaction Monitor

Tasks

Creating a UDP Transaction Monitor

This exercise requires you to use UDP broadcasts to develop a monitor


system for the Web shopping servlets. This system will log all of the
transactions that are performed by the shopping servlets in Module 8.

1. From your home directory, change directory to mod7-


longcon/lab. This directory contains the solutions from Module
8. This directory also contains:

▼ A UDPBroadcaster class (defined in UDPBroadcaster.java).


This class contains two constructors: one that accepts a
broadcast, and one that accepts a broadcast address and source
port. Both constructors create a UDP datagram socket. This
class also contains a public method called send for sending
data to the UDP datagram socket.

▼ A UDPMonitor class (defined in UDPMonitor.java). This class


displays all messages sent to a specific broadcast port. The port
that the UDPMonitor class uses to listen must match the port
used by UDPBroadcaster to send the datagram. This port has
been set to 12345.

7-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a UDP Broadcast Transaction Monitor

Tasks

Creating a UDP Transaction Monitor (Continued)

2. Edit each of the .java files in the mod7-longcon/lab directory.

▼ Create an instance of the UDBBroadcaster class in the


appropriate place(s) in the ShopLogin, ShopBuy, and/or
ShopManage servlet. You will need to know the broadcast
address used in your classroom. Your instructor will supply
you with this address. Refer to Appendix D, “Java Socket
Programming,” for additional information on determining a
broadcast address. For example:
broadcaster UDPBroadcaster("255.255.255.255");

Note – The local broadcast address must be registered in the naming


service of your machine if you are using JDK 1.1.x. Your instructor will
have registered the broadcast address in your hosts or other naming
services file.

✓ This restriction appears to have been lifted in JDK1.2.x . Students can use address
255.255.255.255. However, this address could cause traffic outside of the classroom (if a
classroom router is configured to forward broadcasts to this address).

▼ Identify one or more locations in ShopLogin, ShopBuy, and


ShopManage where a broadcast message might be sent. Use
UDPBroadcaster’s send method to create and send a broadcast
message from within each of these servlets. The send method
accepts a string message. Put the hostname of your machine at
the beginning of each of the strings that your servlets generate.
For example:
broadcaster.send("fuggles: Login Successful");

Time-Extended Connections 7-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a UDP Broadcast Transaction Monitor

Tasks

Creating a UDP Transaction Monitor (Continued)

3. (Optional) Edit the UDPMonitor.java file and add code to


receive the broadcast messages. You need to add code at the
indicated point in the source (marked /* Add datagram
handling here */) that will:

▼ Create an empty DatagramPacket object, with a buffer space


of 1024 bytes.
▼ Fill the DatagramPacket object with a UDP datagram.

▼ Extract the data from the transmission and create a String


from it.

The rest of the program will then append this String to the
display so that it can be seen.

4. If you did not do the previous step, copy UDPMonitor.java from


mod7-longcon/solutions to mod7-longcon/lab.

5. Save the ShopLogin, ShopBuy, ShopManage, and UDPMonitor


files after you have made changes.

6. Generate .class files for each of the servlets and the monitor
program.

7. Copy ShopLogin.class, ShopBuy.class, ShopManage.class,


and UDPBroadcaster.class to server_root/servlets.

8. Copy ShopUsers.txt to server_root/servlets.

9. Copy ShopLogin.html to server_root/public_html.

10. Invoke the ShopLogin.html Web page.

7-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a UDP Broadcast Transaction Monitor

Tasks

Creating a UDP Transaction Monitor (Continued)

11. Run UDPMonitor.

java UDPMonitor

12. Use the modified Web shopping pages. You should see all of the
transactions for all of the students in the classroom as you and
other students use the Web shopping pages.
✓ Remind students that all transactions from all student workstations are being sent to the
same broadcast address. That is why it was necessary to include the host name for each
machine within each broadcast message string.

Note – You will find that you can run multiple monitors, on different
machines, and they will all display the transaction logs. However, you
might notice a lost log from time to time, and you might find that the
logging does not work if there is a router between your shopping
server and your logging station.

Time-Extended Connections 7-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Exercise: Developing a UDP Broadcast Transaction Monitor

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

7-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish the following:

❑ Define the term time-extended connection

❑ Identify the difference between client-side pull and server-side


push

❑ List four options for maintaining a time-extended connection and


outline the strengths and/or weaknesses of each

❑ Develop a user datagram protocol (UDP) transaction monitor


servlet

Time-Extended Connections 7-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
7
Think Beyond

Can you see security implications in broadcasting or multicasting?


✓ Yes, anyone on the same network can eavesdrop broadcast or multicast messages,
although in many networks this is the case even for directed messages.

Consider how each of the various time-extended connection options


would respond to a temporary network failure. Do they recover if the
network is restored, or do they need recovery code? Do they hang up
if a receiving station fails?
✓ UDP solutions, including broadcast and multicast, are robust in the face of any problems
of this sort. Each packet is sent in isolation, and it does not matter if the client or the
server is killed and restarted; everything picks up from where it left off. TCP-based
solutions, on the other hand, are less forgiving, although they still should not hang up on
the failure of a single listener.

7-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Servlet Security 8

Course Map
This module discusses security topics relevant to Web server and
servlet security.

Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

8-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


the topics presented in this module.

What security features or mechanisms does your Web server provide?


Can you configure or modify the security settings of your Web server?
What classes and interfaces are provided in the servlet API that relate
to security?
✓ Many Web servers now provide support for Secure Sockets Layer (SSL) to enable HTTPS
(HTTP over SSL) sessions.

✓ In addition, access control lists (ACLs) are used to control access to resources, realms
are used to group users and assign different privileges, and various means of user
authentication are provided.

✓ Web browsers are now providing preference settings for digitally signed files and
certificates to further add to security.

✓ Most Web servers provide configuration pages for modifying security information.

✓ The servlet API provides the following packages and classes related to security:

• java.security.acl

• javax.net.ssl

• com.sun.security.acl

• com.sun.security.ssl

• com.sun.server.realm
• com.sun.server.http.security

• com.sun.server.security

• com.sun.server.https

✓ A comparison of Java Web Server to other Web servers (against various features) can be
found at http://webcompare.internet.com/chart.html. For a listing of the features of Java
Web Server, see http://webcompare.internet.com/compare/javaweb.html.

8-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Objectives

Upon completion of this module, you should be able to

● Identify the three major threats to Web server security

● Explain the three HTTP security mechanisms supported by the


Java Web Server

● Discuss server features specific to the Java programming language,


such as simple administration, security administration, and servlet
sandboxing

● Describe how access control lists and realms are used, both on
Web servers and by programmers

● Write a servlet that performs basic authentication and investigate


digest authentication

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Java Web Server. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
webserver/index.html.
● Refer to the section “Security” of the Web page Inside the Java Web
Server. [Online]. Available:
http://java.sun.com:80/features/1997/aug/jws1.html.
● Refer to the section “Security Features” of the Web page Java Web
Server 1.1 – The Java Servlet API. [Online]. Available:
http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/api.html.
● Java Web Server 1.1 – Servlet Sandbox. [Online]. Available:
http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/security/sandbox.html.
● HTTP/1.1 – Proposed Standard RFC 2068. [Online]. Available:
http://www.w3.org/Protocols/rfc2068/rfc2068.
● Digest Access Authentication. [Online]. Available:
ftp://ftp.isi.edu/in-notes/rfc2069.txt.

Servlet Security 8-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Major Threats to Web Server Security

The following are major threats to Web server security:

● Theft or alteration of data – Computer theft is a major concern,


but the risk of sensitive data contained on those systems falling
into the wrong hands is critical. Protecting sensitive data through
encryption can make stolen information almost useless.

● Malicious code – Code or computer instructions that are


damaging or malicious in nature; sometimes referred to as malware
or a programmed threat.

Computer security experts have classified malicious software


using the following terms (taken from Practical UNIX & Internet
Security by O’Reilly & Associates, Inc, Chapter 11, “Protecting
Against Programmed Threats”):

▼ Security tools and toolkits – This software is designed for use


by security professionals to protect their sites, yet unauthorized
individuals can wield them to probe for weaknesses.

8-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Major Threats to Web Server Security

▼ Back doors (or trap doors) – Pieces of code written into


applications or operating systems to grant programmers
unauthorized access, that create security risks for attackers to
exploit.

▼ Logic bombs – Hidden features in programs that go off after


certain conditions are met.

▼ Viruses – Programs that modify other programs on a computer,


inserting copies of themselves.

▼ Worms – Programs that propagate from computer to computer


on a network (these may or may not modify other programs on
the target machines).

▼ Trojan horses – Programs that appear to have one function but


actually perform another function.

▼ Bacteria (or rabbit programs) – Programs that make copies of


themselves to overwhelm a computer system’s resources.
● Eavesdropping – Electronic eavesdropping is a type of data piracy.
An entire computer session of a user can be monitored and
captured for later analysis.

For the most part, Web servers contain free information accessed using
HTTP protocol over the Web. However, these threats involve data that
the Web server administrators have labeled secure. A Web server must
be able to authenticate a user that claims rightful access to secure data
at a target URL, in order to authorize access for that user.

Note – Some of the information in the following sections can be found


at http://jserv.javasoft.com/products/java-server/
documentation/webserver1.0.2/security/
security.html#overview

✓ Another type of attack is a denial of service attack. This attack occurs when a client is
able to tie up system resources (such as memory or processor) by forcing the Web server
to perform a function (such as a complex search) multiple times (usually in a loop). When
this occurs, other clients will not be able to access Web server services.

Servlet Security 8-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Authentication and Authorization

Definition
All browsers can communicate using HTTP protocol with the server at
a target URL to request, receive, and display a Web page. Browsers
and servers seem to communicate silently as they pass information
within request headers and response headers.

This structure, outlined by the HTTP protocol, provides some broad


alternatives for authentication, or determining who is requesting access
to a page, and authorization, or negotiating exactly what access that
user has to a specific URL (or information).

In addition, a Web server can perform some sophisticated and


dynamic functions within this HTTP authentication framework. These
servers can use Java Web Server, or other well-known servlet-enabled
servers such as Apache and Netscape Enterprise Server.
✓ Ask students what they typically see when they attempt to access a URL that contains
protected information.

8-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Authorization and Authentication

Authentication Mechanism Overview


There are three distinct types of authentication mechanisms that help
characterize the dialog between the user and the server as they
negotiate authentication using a protocol.

● A passphrase authentication mechanism involves a client that


presents a secret passphrase (or a shorter password, readily subject
to brute force dictionary attacks). Those phrases are usually
remembered by the user.

● Challenge-response mechanisms involve the server sending data to


the user, and the user sending back some data which is a function
of that data. This is often with the assistance of a hardware token,
but can describe more mundane requests and responses.
✓ Challenge: server says “send the data using XYZ mechanism.” Response: client says “OK,
here it is.”

● Public key protocol mechanisms associate the user with an X.509


public key certificate. The user signs some data derived from the
authentication protocol, and the server can verify it with use of
that certificate.

Passphrase systems are commonly used despite some widely


acknowledged problems, which are most severe when users use short
passwords.

Authorization Process Overview


Within each type of authentication, the server must correlate the
identity of the user with internal information it has about the realm
within which the target resource (URL) lies. The user must belong to a
group that has been granted access to the resource through what is
called an access control list (ACL).

Servlet Security 8-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Types of HTTP Authentication

Overview
Today, most Web servers (including Java Web Server) provide the
following HTTP security mechanisms:

● Basic authentication, for passphrase authentication

● Digest authentication, for passphrase authentication

● Secure sockets layer (SSL) server authentication, for public key


protocols
✓ Let students know that you will discuss each type with real-world examples of how they
are used.

After a brief overview of each type, listed previously, and some


examples of how their usage differs, the upcoming section on security
realms will explain how security realms are actually used during
authorization to attach meaning to authentication. Following that,
there will be a more detailed look at implementing basic authentication.

8-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Types of HTTP Authentication

Basic Authentication
Basic authentication involves a user entering a user name and a
passphrase in response to a challenge by the Web server to pass an
access control check for access to protected data.
✓ Challenge is just a way of saying the Web server displays a dialog box forcing the user to
enter a user name and password before they are granted access to the system.

For example, a Web site that provides a bulletin board, for topical
discussions, enforces registration of a user name to deter posts by
imposters and spammers. An attempt to post for the first time would
result in a graphical challenge dialog box requesting a valid user name
and passphrase.
✓ The access control check is done based on the realm associated with the page and the
ACLs set up for that realm. Realms and ACLs will be explained briefly later.

Java Web Server supports the basic authentication scheme using ACLs.
However, there are two well recognized problems with this standard
HTTP mechanism:

● Basic authentication sends the password over the network as plain


text so any eavesdropper can determine the right password to use.
(Both digest authentication and SSL client authentication protect
against this attack.)

● The server needs to store the passwords in plain text; these are
“shared secrets.” This means that when (not if) a server is broken
into, the attacker gains the right to authenticate as each user. Since
users frequently use the same passwords at many different sites,
this is a threat against both those users and all those other sites.
(SSL client authentication is used to protect against this kind of
attack.)
✓ The content presented here on different authentication types is taken from the HTTP/1.1 –
Proposed Standard RFC 2068 which is available at
http://www.w3.org/Protocols/rfc2068/rfc2068.

✓ Reiterate that the two problems are: password sent as plain text and comparison data kept
as plain text on the server.

Servlet Security 8-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Types of HTTP Authentication

Digest Authentication
Basic authentication’s problem of having plain text passwords is
resolved by digest authentication. With digest authentication, the
password must be known to the server. However, only a small portion
or “fingerprint,” used by both the client and server, is actually
exchanged over the network. Therefore, an eavesdropper cannot read
passwords on their way to your Web server. Although this is safer
than sending the password over the network, the client and other
servers, are still at high risk when the server is successfully attacked.

For example, a software company could allow customers to download


software off of their Web site with a temporary login and password.
While the company may lack proper certificates to do SSL, it still does
not want to send plain text passwords with basic authentication. It
chooses to use digest authentication, implemented with a Java applet
as not all browsers support digest authentication.
✓ As with basic authentication, both parties (client and server) have passwords of valid
users. How this information is stored, set up, and exchanged to begin with is not
specified.

✓ Java Web Server provides basic and MD5 digest authentication.

✓ Digest authentication cannot be easily “replayed” because it uses “salt.” Otherwise,


people could just hack the browser to playback the digest. Salt refers to a unique item of
information that both sides have, such as the date of the access request.

SSL Server Authentication


Users need to have a way to trust that the server to which they send
information—such as a credit card number—is really the server they
think it is. SSL always authenticates the server to the user of a browser;
HTTPS URLs (this is HTTP over SSL) let users know that the server
they are communicating with is what they think it is.

Examples of SSL authentication are all over the Internet now. SSL is
used by financial institutions such as banks who want to allow
customers to securely inquire about their account and transfer funds. It
is also used for on-line purchasing of mail-order products like books
and CDs.

8-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Types of HTTP Authentication

SSL Server Authentication (Continued)


✓ SSL is usually done with the assistance of some third-party Certificate Authority, which
provides a clearly defined level of support for a guarantee that the server is what it says it
is. It also requires support from your Web browser (such as HotJava™) to let users
choose which Web sites and certificate authorities they trust.

Another feature of HTTPS is that, when allowed by both the Web site
administrator and the client using a Web browser, all data sent to or
from the server can be encrypted to allow private communications.
This means that an eavesdropper cannot learn potentially sensitive
information about your personal finances or anything else you manage
on-line.
✓ Assuming both server and client can agree on some encryption mechanism, the data
transferred can be encrypted. This requires some client/server handshaking in order to
arrive at an agreed encryption algorithm.

Servlet Security 8-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Security Realms

Definition
A security realm contains users and groups plus their associated ACLs.
The access control list for a user in a particular realm specifies the
privileges that user is granted to access server resources. Resources
include such things as files, directories, and servlets.

All three types of HTTP authentication require the Web server to have
been configured with security realms.

8-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Security Realms

Definition (Continued)
Users can be grouped for two reasons:

● You need to create different realms for various sites, such as other
virtual hosts, or parts of a given Web site serving diverse
applications.

● You need to create groups of different users (within a given realm)


so that you can extend access privileges more efficiently than
listing the users one by one.
✓ Students should be familiar with most of these features except realms. Information on
realms can be found at http://jserv.javasoft.com:80/products/java-
server/documentation/webserver1.0.2/administration/users.html#100. A realm is a
database of users, groups, and access control lists. It is used to specify which users have
access to the resources of a specific service (for example, the Web Service).

Realms Within Java Web Server


The Java Web Server has the following security realms:

● UNIXRealm – Applies only to users in a UNIX environment. It is


the same database of users as listed by the UNIX getpwent
routines. This realm lets the server use HTTP “Basic”
authentication with users’ UNIX environment passwords.
✓ Note – On the UNIXRealm, it is not possible to add a user through the Java Web Server.
The UNIXRealm is controlled through the DNS database and users must be added through
that mechanism.

● NTRealm – Applies only to users in a Windows NT environment


and therefore is available only in the Win32 version of Java Web
Server.

Servlet Security 8-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Security Realms

Realms Within Java Web Server (Continued)


● defaultRealm – Used for general management of users, groups,
and ACLs.

● CertificateRealm – Used to protect resources for users who are


authenticated using SSL. This realm is packaged only in the
versions of this product that include SSL. Users are authenticated
based on their X.509 certificate.

● servletMgrRealm – Used exclusively for signed servlet support,


which is used primarily by software publishers. It holds the X.509
certificates used to authenticate those publishers.

● SharedPasswordRealm – Supports passphrase authentication, and


also some simple challenge-response protocols. When used with
HTTP, it supports both Basic and Digest authentication.

ACLs are tied to specific realms, so they let your Web site’s
administrator control which users get access to individual Web pages
or trees of such pages.

For example, an on-line bookstore has a group of known authors who


have each been assigned a user login and passphrases in an author
group, within an authorRealm. An ACL covering the resource,
http://secure.booksellers.com/authors/admin.html,
contains an HTML form that uses Power-On Self Test (POST) to send
information to update the author’s various books. The server has been
configured to grant POST permission only for a successful basic HTTP
authentication of the author’s user name and password.

For example, a sales and support staff using a mixture of workstations


runs applet versions of purchasing or bug tracking tools from their
Web browsers. Authorized use of these tools is limited to members of
UNIXRealm and NTRealm who pass a digest authentication with the
user name and password for the workstation in their office.
✓ Java Web Server provides dynamically configurable ACLs.

8-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Security Realms

Realms Within Java Web Server (Continued)


The following section will show how the browser and server negotiate
basic HTTP authentication and provide a more concrete example of
users accessing resources.
✓ Draw a diagram of a box containing two circles. The box is labeled employeeRealm. Each
circle, in the box, represents an employee type whose ACL protects resources available to
that employee type. For example you could have an authors circle and editors circle.

Servlet Security 8-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Basic HTTP Authentication In-Depth

Figure 8-1 shows a decision tree outlining the seven-step process of


basic authentication.
✓ The summary of this figure is: (1) browser makes a request to Web server, (2) Web server
determines if the content is protected (if it is not, page is sent; if it is, check
authorization), (3) check user authorization with basic authentication servlet, (4) if
authorization passes, page is received; if authorization fails, send error.

8-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Basic HTTP Authentication In-Depth

Figure 8-1 describes the process in a flowchart.

Browser
Server
sends URL
Browser

URL Yes Authorization


protected? non-null?

Yes

No

Yes User, pass Decode and


Send page
authorized? compare

No

Encode
Send 401
user:pass

Tried No Show auth.


Browser
displays before? dialog box

Figure 8-1 Flowchart of Basic Authentication

Servlet Security 8-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

The seven basic steps are described here, using an example of a


popular on-line bookstore that wants to provide privileged access to
book authors.

Step One: Browser Sends URL


A user supplies a URL to the browser, which requests it from the
appropriate Web server.

Example - Step One

An author of a book wants to update the on-line information about a


book she is selling through BookSellers Incorporated.

The browser is used to open the author administration page that had
been bookmarked previously,
http://secure.booksellers.com/authors/admin.html

Step Two: Server Determines Whether Page Is Protected


Upon receipt of a URL, the server checks its protection space to see if it
is an unauthorized request.

8-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Two: Server Determines Whether Page Is Protected

Example - Step Two

The BookSellers site has chosen Java Web Server, and the Web
administrator had previously taken the following steps to configure it
using the administration applet under the Security section:

● Within Users, added a unique user name and password within


the defaultRealm for each of the 147 authors.

Note – This is just one approach; creating an authorRealm for the


members is another option.

● Within Groups, added a group called authors belonging to the


defaultRealm. Next, added all authors as Members to the
group.

● Within ACL, created a new ACL authorAcl within the


defaultRealm, then added permission only for group authors
to this ACL.

● Within Resources, added authorAcl the absolute path name


that refers to the following URL so that any URL request within
that subdirectory invokes an authentication check for either the
Basic or Digest authentication scheme:

● http://secure.booksellers.com/authors/

Note – Since the Netscape browser does not support digest, choosing
digest would be feasible only if booksellers.com also provided an
applet of its own that performs the client-side part of digest
authentication, as the Java Web Server has done with
com.sun.server.admin.toolkit.AdminApplet.

In this example, the page is within the protection space described by


defaultRealm, or an alternative, such as authorRealm.

Servlet Security 8-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Three: Web Server Checks for Non-Null Authorization


Header, and Sends Challenge
The Web server searches the request header information that was
passed from the browser during the initial URL request, for a non-null
Authorization header.

The Authorization header, when present, supplies the necessary


user and password challenge information for the secure page.

The browser does not send this information (so the header is null)
until there has been a previous request for authentication on the space
during the session. However, if the browser had already visited the
page and passed authentication, the browser would automatically
supply the header.

The Web server immediately responds with a challenge using the


standard 401 error that includes a response header with the syntax:
WWW-authenticate: basic realm="realm information"

Example - Step Three

The following output is actual text sent from a Web server, showing
the WWW-authenticate header information:
HTTP/1.0 401 Unauthorized
Server: JavaWebServer/1.1.1
Date: Fri, 26 Jun 1998 16:04:36 GMT
WWW-authenticate: basic realm="defaultRealm"
Content-type: text/html
Content-length: 223

8-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Four: Browser Interprets 401 Error as Challenge


The browser receives the 401 error, and the WWW-authenticate
challenge, and parses the type of authentication required. Different
results occur at this point based on the authentication type. For basic
and digest authentication types the Web browser can create a simple
dialog to solicit user and password information. For type SSL, a dialog
that provides x.509 certificate information would ensue.
✓ Since the realm information is supplied, a browser or an automated application that is pre-
loaded with authentication information can automatically respond with a valid user for that
realm, if appropriate.

Step Five: Dialog Box Prompts for User Name and Password
The browser displays a dialog box prompting the user for user name
and password.

Example - Step Five

Author Judy Javaguru might supply the user name javaguru and the
password 2_pro1ifik.

Step Six: Browser Returns Encoded Authentication


Information
The browser encodes the user name and password based on the type
of authentication that has been specified in the error page (the
challenge part of the challenge-response mechanism).

For basic authentication, this information would be encoded into a


binary string using base 64 encoding (but no encryption); thus it
would be sent in plain text across the Internet to the server.

Servlet Security 8-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Six: Browser Returns Encoded Authentication


Information (Continued)
In contrast, if digest authentication were used, the browser would
perform some sort of encoding scheme on the information, like an
MD5 hash. The browser would first append information unique to the
session, similar to the Date header in the 401 error, to avoid replay
attacks.

To receive authorization, the client sends the user ID and password,


separated by a single colon (:) character, within a base64 encoded string
in the credentials:
Authorization: Basic credentials

8-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Six: Browser Returns Encoded Authentication Info

Example - Step Six

The browser would encode the string javaguru:2_pro1ifik and set the
authorization header as follows when it requests the page again. The
browser sends this text, as if it were using TELNET to access port 80 of
the secure.booksellers.com machine.
GET /authors/admin.html HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.05 [en] (X11; I; SunOS 5.5
sun4u)
Host: java-guru-writer.com
Accept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, image/png, */*
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Authorization: Basic amphdmFndXJ1OjJfcHJvMWlmaWs=

Note – The base 64 encoding scheme specified in RFC 1521 (MIME)


takes 3-byte chunks of input and encodes it as four printable
characters. If the input length to be encoded is not a factor of 3 bytes
then either one or two equal (=) signs which indicate padding
characters are appended.

Most browsers will let you preempt the dialog by supplying the user
name and password as part of a URL:
http://jjavaguru:2_pro1ifik@secure.booksellers.com/
authors/admin.html

Opening this URL has the same effect as entering the information in an
authentication dialog, except that anyone looking at your browser will
see your password.

Servlet Security 8-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
The Seven Steps of Basic HTTP Authentication

Step Seven: Server Validates Authentication Information,


Returns Page
The server compares authentication information with database to
validate it. If the authentication information is valid, the server serves
the Web page.

Again, what the server does depends on the type of authentication.


Typically the Web master would create the user name and password
using the administration interface of the Web server and it is stored in
a way similar to /etc/passwd on UNIX systems.

Example - Step Seven

The author would be presented with an HTML form that has an


interface for updating information on books that the author has
written. A review, typographical corrections, or hyper-links to source
code and tool updates can be input.

8-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Implementing Basic Authentication in a Servlet

Even though there are many Web servers that support servlets, many
have different ways of configuring the equivalent of realms, groups,
and ACLs for resources. In addition, a corporate intranet typically has
some sort of password database which is used for legacy applications.

Implementing customer authentication within a servlet is a popular


programming task because it is not usually appropriate to port or
duplicate an existing password database into a form that a particular
Web server supports.

Servlet Security 8-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Implementing Basic Authentication in a Servlet

An Example Basic Authentication Servlet


The following servlet, BasicAuth, closely implements the seven steps
of HTTP authentication:
1 import java.util.*;
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import sun.misc.BASE64Decoder;
6
7 public class BasicAuth extends HttpServlet {
8
9 public void doGet (HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
10 String username = null, password = null,
11 authHeader = req.getHeader ("Authorization");
12
13 if (authHeader == null) {
14 res.sendError (401);
15 return;
16 }
17 try {
18 // Limit authHeader to only the Base64 encoded user:pass
19 authHeader = authHeader.substring (6).trim ();

8-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Implementing Basic Authentication in a Servlet

An Example Basic Authentication Servlet (Continued)


20
21 // Uncompress the binary user:pass into a loginInfo string
22 BASE64Decoder base64 = new BASE64Decoder ();
23 byte mydata [] = base64.decodeBuffer (authHeader);
24 String loginInfo = new String (mydata);
25
26 // Save the plain text user name and password
27 int iindex = loginInfo.indexOf (":");
28 if (iindex != -1) {
29 username = loginInfo.substring (0,iindex);
30 password = loginInfo.substring (iindex+1);
31 }
32 } catch (IOException ioe) {
33 username = (String)null;
34 }
35 // Method validate left unimplemented.
36 // It could reference ACLs or check a database
37 if ( ! validate (username, password) ) {
38 res.sendError (401);
39 return;
40 }
41 // Create an HTML page that shows we have gained access
42 res.setContentType ("text/html");
43 ServletOutputStream out = res.getOutputStream ();
44 out.println ("<HTML><HEAD>" +
45 "<TITLE>Successful Authorization</TITLE>" +
46 "</HEAD><BODY>" +
47 "<H1>Successful Authorization</H1>" +
48 "<EM>Username: </EM> “+ username +
49 "</BODY></HTML>");
50 }
51
52 public String getServletInfo () {
53 return "Basic Authentication missing validate method";
54 }
55 }
56

Servlet Security 8-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Implementing Basic Authentication in a Servlet

Steps in Example Basic Authentication Servlet


The seven steps from the previous section correspond to the servlet
code as follows:

1. Browser URL request occurs on client.

2. The Web server resolves the URL to point to this servlet, whether
directly or indirectly, and invokes doGet method with potential
Authorization header stuffed into the HttpRequest (line 9).

3. The servlet checks for a browser-set (non-null) Authorization


header containing user name and password (lines 13–16).

4. The servlet sends a 401 error page that includes an automatically


set WWW-authenticate header based on the realm that protects
the URL that just invoked this servlet.

An alternative approach is to set the WWW-authenticate header


manually, and use setStatus to generate the 401 error:
res.setHeader ("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
res.setStatus (HttpServletResponse.SC_UNAUTHORIZED);

5. Browser receives user name and password (lines 22–31).

6. Browser re-invokes doGet through server, this time with


Authorization set to contain base64-encoded user:pass.

7. On lines 19–40 the user name and password are decoded and the
validate method (undefined) returns a Boolean indicating whether
the password is valid.
✓ Some other interesting points in the code are lines 13–15 and 37–39; they create
challenges.

8-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Examples of Server-Independent Validation

By implementing the validate method in a variety of ways, you can


gain control over exactly how your Web server, or servlet application
framework is protected.

In the exercise at the end of this module, TestBasicAuth


implements a stub class AccountManager with a validate
(username, password) that is hard-coded to require a user to use
the name of duke and the password servlets.
✓ Normally, you would not want to hard code user names and passwords in your code.

Some things that validation can do are

● Access a relational database through JDBC, an object database


through Object Database Management 2 (ODGM2), or an
Enterprise Bean any number of ways

● Access a middle-tier server through RMI or CORBA/IIOP and


Java IDL

● Do a flat file password lookup

Servlet Security 8-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Example of Server-Independent Validation

● Assign a one-time password for a client using a device such as an


Enigma card

● Perform a translation between a complex legacy permission


system using a package that implements the Realm, Group, and
ACL classes from java.security (a current implementation of
these is in sun.server, which is what the Java Web Server uses)

The discussion of servlets and security leads into topics on securing


servlets and the Java Web Server in the sections that follow.
✓ RemoteUser is particularly important to cover for the lab.

8-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Additional Security Features Java Web Server


✓ In addition to Java Web Server, another example of a Java server which is in development
is the Webtop Server (see http://jserv.javasoft.com/products/java-server/ncserver/
index.html). The API licensees are also hard at work creating a wide variety of servers
based on the Java programming language.

Secure Administration and Servlet Sandboxing


The following are additional security features the Java Web Server
provides:
● Secure administration – By default, the JavaServer administration
pages are controlled through HTTP digest authentication. In
addition, these pages can be accessed through HTTPS. When you
configure your Java Web Server, you are configuring a Web server
to use SSL. This protocol combination is called HTTPS (HTTP with
SSL). Therefore, administrative operations are protected from
certain “active wiretapper” attacks and can be kept private.
● Servlet sandboxing – Servlets, like applets, can be isolated into
predefined, secure areas (sandboxes) that significantly reduce the
enterprise’s exposure to security risk.
✓ The Adrenaline Group has a list of Internet Service Providers (ISP) using the Java Web
Server at http://www.adrenalinegroup.com/jwsisp.htm.

Servlet Security 8-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Additional Security Features of JavaWeb Server

Secure Administration With SSL

Note – The following information is taken from


http://jserv.javasoft.com:80/products/java-server/
documentation/webserver1.0.2/security/ssl.html.

You can have Java Web Server use the secure Web service when it is
started by highlighting Secure Web Service from the initial window
and clicking on Start. In its normal usage, SSL provides up to four
features to your TCP connections:

● Your Web server is authenticated to its clients, so that they can tell
who you “really” are. Public key certificates are used for this
authentication.

● All requests to your Web server are encrypted so that client data
(such as credit card data) is kept confidential (as are the responses
from your Web server).

8-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Additional Security Features of Java Web Server

Secure Administration With SSL (Continued)


● The data is protected against being tampered with by a third party.
This is called integrity protection.

● When appropriate, clients can authenticate themselves to your


server using their own Public Key certificates.

There are several different ways to use SSL. In particular, each of the
four features comes in several varieties, and all except integrity
protection are optional.

Servlet Security 8-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Additional Security Features of Java Web Server

Servlet Sandbox
The Java Web Server provides a controlled execution environment, a
servlet sandbox analogous to the applet sandbox used by Web browsers
to control applets.

All Java servlets that are remotely loaded are untrusted. Untrusted
Java servlets are invoked by separate instances of a dispatcher servlet
and run in a thread that is part of an isolated thread group in the
servlet sandbox. The service handler must send requests through the
dispatcher servlet to a thread in that sandbox, and wait for it to
complete. The cost of a request for an untrusted Java servlet is
therefore higher than for local Java servlets.

8-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Additional Security Features of Java Web Server

Servlet Sandbox (Continued)


Figure 8-2 shows the dispatcher servlet’s interaction with the servlet
sandbox.

Servlet sandbox Dispatcher


servlet invocations

Untrusted Untrusted
servlet servlet
Isolated thread groups

Untrusted
servlet

Figure 8-2 Servlet Sandbox

✓ The faq.html file included with the Java Web Server (JWS) documentation states: Servlets
installed into the servlets directory are considered local servlets and are not
"sandboxed." That is, these servlets are not under the protection of the Security Manager.
For maximum security, do not install untrusted servlets in the servlets directory.

Servlet Security 8-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Additional Security Features of Java Web Server

Servlet Sandbox (Continued)


The servlet sandbox will protect access to the following Java Web
Server resources:

● Files

▼ Web pages served by Java Web Server

▼ Data used to operate each servlet

▼ Other files on the file system

● Runtime state

▼ Threads controlled by other servlets

▼ Security context of other servlets

▼ Private keys used to authenticate this server

● Administrative state

▼ Users and groups

▼ ACL entries (including ones controlling the sandbox)

● Network servers

● Other resources controlled by security manager objects

8-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Servlet Types

Use of the JDK™ code signing facility (digital signatures and


certificates) allows a new level of policy flexibility to be granted to the
Web site administrator. New modes of operation will be supported,
and that servlets will come in four types:

● Trusted servlets – Servlets that are granted full access to the


system. There are two types of trusted servlets:

▼ Java Web Server internal servlets – Some parts of the Java Web
Server are implemented using trusted internal servlets.

▼ Local servlets – The Java Web Server can be configured with a


single directory of local servlets, which are provided by the site
administrator. These have a class loader that reloads the
servlets when they have been modified, and that class loader is
recognized explicitly by the security manager.

Servlet Security 8-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Servlet Types

● Signed network servlets – All network servlets execute in the


servlet sandbox. If the servlet was signed by one of a set of signers
identified by the Web site administrator, the sandbox allows full
access. (It can access the file system, remote hosts, and so on.)
Servlets that were signed, by entities not trusted by the Web site
administrator, will be treated like unsigned network servlets.

Note – Servlets that have been digitally signed as they were put into
Java Archive (JAR) files can be trusted and granted more permissions
by the security manager. A digital signature on executable code
indicates that the organization which signed the code “vouches for it”
in one sense. Such signatures cannot support accountability by
themselves, but they do indicate a degree of assurance that can be
placed on use of that code.

✓ For background information on digital signatures and certificates, refer to the SL-303
Implementing Java Security course or see
http://java.sun.com/marketing/collateral/security.html.

● Unsigned network servlets (untrusted servlets) – Unsigned


network servlets are constrained by the sandbox; they execute
without privilege and can access the file system, network, and so
on.

Trusted servlets should, of course, not abuse the trust placed in them.
They have access to the server’s private encryption keys, to the file
system, and to the network. They could even call the System.exit
method which will unload the Web server.
✓ In the future, the control granted by the sandbox is likely to be made even more flexible.
Specifically, an ACL associated with a given Web server will define what basic privileges
are extended to which signers, and ACL entries used to control access to Web resources
will be appropriately applied to requests coming through servlets. For example, on a given
host the Web server operating on port 80 might use a different ACL than the one running
on port 8080, and if the host uses multihoming, each Web server on port 80 could have a
different ACL.

8-38 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

RemoteUser Property

Overview
Upon authentication of any sort (basic, digest, or SSL) the property
RemoteUser is set by the Web server within an HTTP header. It is
available within a servlet through a call to getRemoteUser on the
request object. For those familiar with CGI scripts, this property is
the same as the CGI variable REMOTE_USER.

Prior to authentication, the RemoteUser property is null. There are


two reasons why this property is useful in servlet programming:

● The servlet can be written so that it can detect a non-null value


from the getRemoteUser method and determine if the user has
been authenticated in some way through the server.

This leaves the servlet code independent from specific


authentication protocols and facilitates its reuse.

Servlet Security 8-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
RemoteUser Property

Overview (Continued)
● A group of servlets can be used to depend on the RemoteUser
property for a session without passing extra login information.
✓ The easiest way to set this scenario up is to use the administration applet’s Security ➤
Resources, using defaultAcl, and protect the path to the SnoopServlet. Then use the
jeeves or admin password that comes configured for that ACL and access the servlet.

You can use the administration applet to set up a realm, an ACL for
the realm, users for the realm, and resources that the ACL controls.
Then have your servlet check the RemoteUser property using the
getRemoteUser method to verify that some type of authentication
took place.

Checking the RemoteUser Property


✓ The SnoopServlet code in the doc/servlets directory of the Java Web Server (JWS) toolkit
uses the getRemoteUser method.

The following code fragment illustrates checking the RemoteUser


property:
1 public class RemoteUserTest extends HttpServlet {
2
3 public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
4 String remoteUser;
5 ...
6 remoteUser = req.getRemoteUser()
7
8 // code to check if remoteUser non-null and act accordingly
9 ...
10 }
11

8-40 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Sanity Checking

In most cases, you will be creating both servlets and the interfaces that
communicate with your servlets (such as HTML pages, applets, and
applications). Therefore, you will have full knowledge of the types of
parameters a request should contain. It is important, for security
reasons, to perform a sanity check on request parameters. This is
especially true if the parameters you expect to receive access a volatile
portion of your Web server.
✓ This is a recommendation issued by the Java Software Division (formerly JavaSoft).

Servlet Security 8-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8

Review of Servlet Security

Generally, Web servers offer several security features that can be built
into servlets. These features include

● Basic authentication–User name/password combinations in “plain


text.”

● Digest authentication–User name/password combinations that are


not sent over the wire.

● SSL server authentication–Encrypted messages based on certificate


authorities.

● Web server implemented realms–combined users, groups, and


ACLs. Java Web Server supports several common realms.

8-42 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Review of Servlet Security

● There are seven steps in basic HTTP authentication:

▼ Browser sends URL.

▼ Server determines page is protected.

▼ Web server checks for non-null authorization header and sends


challenge.

▼ Browser interprets 401 error as challenge.

▼ Dialog box prompts for user name and password.

▼ Browser returns encoded authentication information.

▼ Server validates authentication information and returns page.

● Java Web Server also provides secure administration (SSL) and


servlet sandboxing.

▼ SSL offers client identification, encryption, and integrity


protection.

▼ Servlet sandboxing places untrusted servlets, such as remote


servlets, in a sandbox.
● Other servlet types are: trusted servlets (internal and local servlets)
and signed network servlets.

● The RemoteUser property can be checked to ensure that a user has


been authenticated to the system.

Servlet Security 8-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercise: Basic and Certificate Authentication Servlets

Exercise objective – The objective of the first exercise is to create a


servlet that does basic access authentication by displaying a
user/password dialog box to validate user name and password pairs.
The objective of the second exercise is to examine a certificate
authority.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.
✓ Spend some time discussing possibilities for how passwords are stored and checked. The
program used in this exercise hard codes the password into the program code (see the
validate method of the class AccountManager in the program). Some possibilities include
verifying the password from some file on a server or from a database.

8-44 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercise: Basic and Certificate Authentication Servlets

Tasks

Creating a Basic Authentication Servlet

1. From your home directory, change directory to mod8-secure/lab.

2. Edit the file TestBasicAuth.java. Look for the comment


STUDENTS DEFINE METHOD getAuthUserName HERE and
define the getAuthUserName method used in the doGet method of
this program such that:

▼ An HttpServletRequest object is an argument to this


method.

▼ The return value for this method is an array of strings.

▼ The first element in the array that is returned is the user name.

▼ The second element in the array that is returned is the


password.
✓ Students can use the sample code found in this module for much of the code needed to
define this method.

3. Compile the TestBasicAuth.java file:


javac TestBasicAuth.java

4. Copy TestBasicAuth.class and AccountManager.class to the


server_root/servlets/.

5. Open the following URL:

host_name:9090/

6. Enter the following information:

user: admin
password: admin

Servlet Security 8-45


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercise: Basic and Certificate Authentication Servlets

Tasks

Creating a Basic Authentication Servlet (Continued)

7. Select Web Service and click on Manage.

8. Click on Servlets.

9. Click on Add.

10. Enter the following information:

Servlet Name: testbasicauth


Servlet Class: TestBasicAuth

11. Click on Add.

12. Click on Setup.

13. Select Servlet Aliases.

14. Add the following information:

Alias: /testbasicauth.html
ServletInvoked: TestBasicAuth

Note – Refer to Appendix B, “Using Java Web Server,” for more


information regarding servlet aliases.

15. Click on Save.

16. Close the window.

8-46 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercise: Basic and Certificate Authentication Servlets

Tasks

Creating a Basic Authentication Servlet (Continued)

17. Go to the following URL:

http://host_name:8080/testbasicauth.html

18. Enter the following user name and password:

User Name: illegaluser

Password: illegalpassword

19. Click on OK.

You should get the following message:

Authorization failed. Retry?

20. Click on OK and try again with the following user name and
password:

User Name: duke

Password: servlets

21. Click on OK.

You should see a page with a message Successful Authorization


containing some information about your headers, and both your
encoded and plain text user name and password.

Servlet Security 8-47


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercise: Basic and Certificate Authentication Servlets

Tasks

Investigating a Certificate Authority Servlet

The Java Web Server includes examples of various servlets, including a


certificate authority servlet.

1. Analyze the source code for the certificate authority servlet in


mod8-secure/examples/CA.java. The certificate authority
servlet demonstrates the following:

▼ Use of HTML forms with the POST method

▼ Use of the ServletUnavailable exception for reporting fatal


initialization time errors

▼ Dynamic generation of non-HTML data by a servlet

▼ Some relatively complex parsing for the form parameters

▼ Integration with the KEYGEN extension in Netscape Navigator™

▼ Use of the sun.security.x509 package in JDK 1.1 (being


augmented by public Java APIs in a later version of the JDK) to
create and sign public key certificates

▼ Some of the basic functionality of a Certificate Authority, such


as VeriSign

Optional – Browse the RFCs

The lab directory for this module contains a subdirectory called RFCs.
This subdirectory includes the RFCs mentioned in the lecture material:
RFC 2068 and RFC 2069. If you are interested, you can look through
what is specified in each of these.

8-48 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Exercises: Basic and Certificate Authentication Servlets

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

Servlet Security 8-49


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Identify the three major threats to Web server security

❑ Explain the three HTTP security mechanisms supported by the


Java Web Server

❑ Discuss server features specific to the Java programming language,


such as simple administration, security administration, and servlet
sandboxing

❑ Describe how access control lists and realms are used, both on
Web servers and by programmers

❑ Write a servlet that performs basic authentication and investigate


digest authentication

8-50 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
8
Think Beyond

How might security be implemented in the exercises used throughout


this course?

Servlet Security 8-51


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Servlet Beans 9

Course Map
The JavaBeans architecture can be used to create server-side servlet
components. This module addresses the issues involved with creating
a Java servlet that is also a Bean.
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

9-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following question is relevant in understanding the


topics presented in this module.

What are some of the advantages of integrating the JavaBeans


architecture, a component architecture, into a servlet?

✓ Servlets that are Beans can store state-related values in a persistent form. Thus, a servlet
Bean can retain its state if a server were to go down.

✓ Changes to a servlet Bean occur immediately.

✓ A servlet that is a Bean or interoperates with other Beans gains advantages like code
modularity and interoperability with Bean-aware rapid application development tools used
to create, import, and integrate Beans into applications.

9-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Objectives

Upon completion of this module, you should be able to

● Define the terms JavaBeans, Bean, and servlet Bean

● List the four types of functionality most Beans provide

● Explain the two ways to pass properties to servlet Beans

● Describe how to package and install servlet Beans

● List the three ways of invoking servlet Beans

● Develop a servlet Bean

● Invoke a servlet Bean using Java Web Server and an .shtml Web
page

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Java Servlet Tutorial. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/
servlet_tutorial.html.

● Using Servlet Beans. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1/servlets/bean_use.html.

● Using JavaBeans in Servlets and in JHTML Files. [Online]. Available:


http://jserv.javasoft.com/products/
java-server/documentation/webserver1.1/servlets/
bean_use.html.

Servlet Beans 9-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

What Is JavaBeans?

JavaBeans is a portable, platform-independent component model


written in the Java programming language. You can develop Beans,
reusable software pieces, by writing Java classes that adhere to the
JavaBeans component model These Beans can be combined, using an
application development environment that supports the JavaBeans
component model, to create robust cross-platform applets and
applications. For example, several math Beans, created by one
developer, might be connected to a graphing Bean, from another
developer, to create part of a charting application. The JavaBeans
architecture was built through a collaborative industry effort and
enables developers to write reusable components in the Java
programming language.

9-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Functionality of Beans

Bean components can vary in the functionality they provide. However,


the following features are typical of most Beans:

● Beans are introspectable. Through the use of the Java reflection


APIs, Beans can publish Bean properties (state-related values held
by the Bean) and event methods. Other applications, like a rapid
application design tool, can then use introspection to “discover”
these properties and event methods.

● Beans are event aware. Beans use the JDK 1.1. events system to
communicate with each other.

● Beans are customizable. Beans can have graphical user interface


(GUI) editors that allow Bean programmers to configure the Beans
during application design time.

● Beans can be persistent. Beans can serialize themselves (save


copies of themselves to a .ser file) to retain state-related values.

Servlet Beans 9-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

What Is a Servlet Bean?

Definition
A servlet can access other Beans, or a servlet can be a Bean. A servlet
Bean is a servlet that adheres to the JavaBeans design patterns,
particularly the design pattern for introspection. Simply put, a servlet
becomes a servlet Bean when it implements get and set accessor
methods to access state-related values within the servlet.
✓ Students might ask about server-side Beans development tools. At the time of writing this
module (4/98), there were no GUI tools available to test servlet Beans. However, this is a
plausible concept and may be a part of some of the Beans tools soon. You should be able
to load servlet Beans into current GUI tools to configure them and create their persistent
forms.

✓ A GUI tool would have to have its own servlet invoker to actually run servlets.

✓ Servlet Beans offer two advantages over servlets: changes to a servlet Bean automatically
take place and their state can be easily persisted.

9-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
What Is a Servlet Bean?

An Example Servlet Bean


The following sample code is for the SampleBean servlet Bean:
1 import javax.servlet.http.*;
2
3 import java.io.PrintWriter;
4 import java.io.IOException;
5
6 public class SampleBean extends HttpServlet {
7 private String stringProperty = "Hello World";
8 private int intProperty = 0;
9
10 public void doGet(HttpServletRequest req,
11 HttpServletResponse res) throws IOException {
12
13 // Set response headers:
14 res.setContentType("text/html");
15 res.setHeader("Cache-Control", "no-cache”);
16
17 // Emit current properties setting:
18 PrintWriter writer = res.getWriter();
19 writer.println("<HTML><HEAD><TITLE>SampleBean
</TITLE></HEAD><BODY>");
20 writer.println("<P>SampleBean current configuration:");
21 writer.println("<TABLE border><tr>");
22 writer.println("<TH align=\"center\">Property</th>");
23 writer.println("<TH align=\"center\">Value</th>");
24 writer.println("<TH><td>stringProperty<td>"
+ getStringProperty());
25 writer.println("<TR><TD>intProperty<td>"
+ getIntProperty());
26 writer.println("</TABLE>");
27 writer.println("<P>Go to the admin to change these Bean properties
!");
28 writer.println("</BODY></HTML>");
29 }

Servlet Beans 9-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
What Is a Servlet Bean?

An Example Servlet Bean (Continued)

30 /**
31 * Bean property accessor - Get the <tt>stringProperty</tt> value.
32 * @return A String instance, or <tt>null</tt>
33 */
34 public String getStringProperty(){
35 return stringProperty;
36 }
37
38 /**
39 * Bean property accessor - Set the <tt>stringProperty</tt> value.
40 * @param A String instance, or <tt>null</tt>
41 */
42 public void setStringProperty(String stringProperty){
43 this.stringProperty = stringProperty;
44 }
45
46 /**
47 * Bean property accessor - Get the <tt>intProperty</tt> value.
48 * @return The integer value for the property.
49 */
50 public int getIntProperty(){
51 return intProperty;
52 }
53
54 /**
55 * Bean property accessor - Set the <tt>intProperty</tt> value.
56 * @return The new value for that property
57 */
58 public void setIntProperty(int intProperty){
59 this.intProperty = intProperty;
60 }
61 }

9-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

What Is a Servlet Bean?

Setting Header Information


The res.setHeader API enables you to add a field to the response
header with the given name and value. If the field had already been
set, the new value overwrites the previous one. The
res.containsHeader method can be used to test for the presence of a
header before setting its value. The header fields definitions for HTTP
1.1 are documented in RFC 2068.

Setting Cache-Control

The example uses the Cache-Control header field to specify


directives that must be obeyed by all caching mechanisms along the
request/response chain (line 15). The no-cache attribute is used to
ensure that requests and responses are not cached. This attribute is
often necessary when information from a previous request must be
overwritten, not returned from a cache, by information from another
request.

Servlet Beans 9-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
What Is a Servlet Bean?

Setting Header Information

Setting Cache-Control (Continued)

For example, a servlet that returns stock quotes might implement this
feature to ensure that all stock quotes on a browser are current.

Note – The mod2-forms/examples directory contains a copy of RFC


2068. This RFC describes the HTTP 1.1 protocol.

9-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

What Is a Servlet Bean?

get and set Accessor and Mutator Methods


Next, the get and set accessor methods are called, within the
example’s service method, to get the current value of a property and
print it as part of the response (lines 24–25).

Properties in ServletConfig

Properties are passed to the init method using the ServletConfig


object. These properties must be configured manually with the Java
Web Server properties editor.

Introspected Properties

Java Web Server can also discover the properties that a servlet Bean
contains through introspection. Java Web Server examines servlet
Beans to determine property names when a servlet Bean is configured.

Servlet Beans 9-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
What Is a Servlet Bean?

get and set Acessor Methods

Introspected Properties (Continued)

Properties are identified by the names of their get and set accessor
and mutator methods (lines 34, 42, 50, 58). Java Web Server will
automatically list the property and its default value within its property
editor.

The example contains two sets of get and set accessor methods:
public void setStringProperty(String stringProperty)
public String getStringProperty()

public void setIntProperty(int intProperty)


public int getIntProperty()

Two properties, stringProperty (with a default value of HelloWorld)


and intProperty (with a default value of 0), will be displayed in the
properties editor when this example is configured within Java Web
Server.

You can change the default values for these properties using Java Web
Server if your servlet Bean supports JavaBeans design pattern for Bean
persistence.

The properties editor will also create a servletInfo property for any
servlet that is configured as a servlet Bean (regardless of whether the
servlet Bean overrides getServletInfo).

Note – The mod9-beans/examples/ directory contains a copy of the


SimpleBean servlet Bean source code and Java archive (JAR) file.

✓ There are some requirements your class needs to follow to be seen as a Bean: the class
must be serializable, public, and contain a default constructor.

✓ Accessor methods are the get methods. Mutator methods are the set methods.

9-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Servlet Beans Persistence

Implementing java.io.Serializable
Your servlet Bean must implement java.io.Serializable (or
java.io.Externalizable) to make its fields persistent. Implementing
Serializable allows Java Web Server to create a persistent form of
your Bean when you configure the Bean.

Writing to a Serialization File


If you want your servlet to update the instance data within a .ser file,
you will have to follow the JavaBeans guidelines for writing to
serialized files. For example, you might want your servlet Bean’s
destroy method to save the state of a servlet Bean before the server is
shut down.

Servlet Beans 9-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Servlet Beans Persistence

Writing to a Serialization File (Continued)


Java Web Server automatically creates a new servlet Bean instance,
using the persistent form of the servlet Bean (if one exists) when it
loads the servlet Bean.

Note – Java Web Server only creates .ser files for Bean classes that are
within a JAR file.

✓ The exercise within this module guides students through configuring a servlet Bean and
creating the .ser file.

9-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Servlet Beans Persistence

An Example of Writing to a Serialization File


The following code can be used for writing the state of a servlet Bean
to a serialized stream:
1 try {
2 String serFile =
3 "/opt/JavaWebServer/servletbeans/SampleBean.ser";
4 ObjectOutputStream os = new ObjectOutputStream (
new FileOutputStream (serFile));
5 os.writeObject(this);
6 os.flush();
7 os.close();
8 } catch (Exception e) {
9 log ("destroy: Exception caught");
10 }
11 }

Writing objects, and a Bean component in particular, to a serialized


stream is a simple process. The ObjectOutput interface is
implemented by the ObjectOutputStream class. You can use the
writeObject method defined by the ObjectOutputStream class to
write your Bean.

The class of the object, the signature of the class, and the values of the
non-transient and non-static fields of the class and all of its supertypes
are written by the writeObject method. The writeObject method
throws both IOException and ClassNotFoundException.
✓ GenericServlet implements Serializable. Therefore, all you need to do is subclass
GenericServlet (which is what HttpServlet does).

Servlet Beans 9-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Packaging Servlet Beans

Serialized servlet Bean files, and the class file they reference, can be
packaged together in a JAR file. Serialized Beans (.ser files) within a
JAR file cannot be modified by Java Web Server or your servlet. If you
want to keep modifiable persistent forms of your Beans, they will have
to reside outside of the JAR file.

Java Web Server will create .ser files when you initially add and
configure a new servlet Bean whose classes reside in a JAR file. This
.ser file will have the same name as the servlet Bean class. You can
use Java Web Server to further modify and save property values
within this newly created .ser file. Java Web Server creates .ser files in
the server_root/servletbeans directory. If a serialized form of the
servlet Beans exists, Java Web Server will automatically read it and
update the servlet’s state with the saved state.
✓ Apparently Java Web Server lets you configure Beans that do not reside in a JAR file;
however, Java Web Server does not seem to recognize Bean properties unless they are in
a JAR file.

9-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Servlet Bean Instantiation

Class Loader for Deserializing Beans Files


Java Web Server provides support for instantiating servlet Beans by
providing a class loader that deserializes the servlet Beans files from
.ser files. These .ser files can be outside or inside in a JAR file. When
a JAR file changes on disk, the class loader automatically reloads it.
✓ Java Web Server saves the Bean in servlet_class.ser and instantiates the class with
Beans.instantiate (servlet_class).

Locations for Servlet Beans


Servlet Beans files can reside in server_root/servlets/,
server_root/servletBeans, or any directory included in the
CLASSPATH.
✓ As with a plain servlet, if the servlet exists in the CLASSPATH it will not be reloaded
automatically.

Servlet Beans 9-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Servlet Bean Instantiation

Automatic Reloading of Servlet Beans


To take advantage of the automatic reloading feature of the JavaServer,
store your servlet Beans files (.class, .ser, and .jar files) in the
servletbeans directory and do not include it in the CLASSPATH.
(Automatic reloading is not performed on files residing in directories
in the CLASSPATH.)
✓ The Java Web Server will add any .jar file in the server_root/lib directory to its
classpath on startup only. This is handled by the shell scripts included by the Java Web
Server. Loose classes in the lib directory will not be found unless you add
server_root/lib to your class path.

9-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Invoking Servlet Beans

You can invoke servlet Beans the same way you would invoke any
other servlet, after a servlet Bean is loaded. However, there are some
items to consider when accessing a servlet Bean using a URL.

Invoking Servlet Beans Using a URL


Servlet beans can be invoked by calling them as a URL address. Even
though you installed the servlet Bean in the
server_root/servletbeans/ directory, you call it with a servlet/
URL. The server will search the servletbeans/ directory for the
appropriate file.
http://host_name:port/servlet/ServletName

ServletName represents either the name of the servlet Bean class file
or a .ser file. Invoke a class file or serialized file using the name of
the file without the .class or .ser extension.
✓ In the case of the .ser files, the JAR is normally in the same directory.

Servlet Beans 9-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Invoking Servlet Beans

An Example of Invoking a Servlet Bean Using a URL


For example, suppose a server_root/servletbeans/ directory
contains the files Counter.class, counter1.ser, and a JAR file,
Hello.jar. The JAR file contains the files Hello.class, hello1.ser,
and hello2.ser.

The two .ser files, hello1.ser and hello2.ser, contain alternate


greetings for the servlet. The hello1.ser file contains the property
greeting=”Good Morning” and hello2.ser contains the property
greeting=”Good Evening.” Notice that the Hello.class file’s source
code contains the property greeting=“HelloWorld.” Figure 9-1 shows
each of these files.
server_root/

... servletbeans/ ...


Hello.jar
Hello.class
hello1.ser
hello2.ser

Counter.class
counter1.ser

Figure 9-1 Example Servlet Bean Files

9-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Invoking Servlet Beans

An Example of Invoking a Servlet Bean Using a URL


(Continued)
The Hello.class creates a Web page with a greeting. Below is a code
fragment from Hello.java.
1 String greeting = "Hello World"
2
3 //code to get, set, and display greetings
4 public String getGreeting {
5 return greeting;
6 }
7
8 public void setGreeting(String g){
9 greeting = g;
10 }
11
12 public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
13 PrintWriter out;
14
15 res.setContentType("text/html");
16 out = res.getWriter();
17
18 out.println("< html >");
19 out.println("< head >< title &gtGreeting < /title> < /head >");
20 out.println("< body >");
21 out.println("< h1 >" + getGreeting() + "< /h1 >");
22 out.println("< /body > < /html >")
23 }

Servlet Beans 9-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Invoking Servlet Beans

An Example of Invoking a Servlet Bean Using a URL


(Continued)
You can use three separate URLs to get three different greetings:

● The invocation http://host_name:port/servlet/hello1


returns "Good Morning"

● The invocation http://host_name:port/servlet/hello2


returns "Good Evening"

● The invocation http://host_name:port/servlet/Hello


returns "Hello World"

Note – None of the .ser files in this example would be modifiable


using the Java Web Server properties editor.

9-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9

Review of Servlet Beans

Servlet Beans are servlets that adhere to the JavaBeans design pattern
for introspection. A servlet Bean can adhere to all of the JavaBeans
design patterns. The following information was discussed regarding
servlet Beans:

● Java Web Server’s property editor will automatically recognize the


properties within your servlet through introspection. This requires
you to create get and set accessor methods that include the name
of each property.

● Implement the java.io.Serializable or


java.io.Externalizable interface if you want Java Web Server
to create a persistent form of your servlet when it is configured.

● The servlet Beans that you create should be packaged in JAR files.

● A serialized form of your servlet Bean will be created, outside the


JAR file, when you configure your Bean. This .ser file will have
the same name as the servlet Bean’s .class file.
✓ If a .ser file already exists, it will be used.

Servlet Beans 9-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Review of Servlet Beans

● Put servlet Beans in the server_root/servletbeans directory


to benefit from Java Web Server’s automatic reloading feature.

● Invoke servlet Beans by specifying their .class or .ser files.

9-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Exercise objective – Develop a servlet Bean using standard Beans


functionality such as introspection and serialization. Alter a servlet
Bean to be persistent, allowing it to save its state upon servlet
termination. Create an advanced counter servlet Bean.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

Servlet Beans 9-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Creating the CounterBean Servlet Bean

The CounterBean servlet Bean will be used to keep track of the


number of times a Web page is accessed (called hits). Each time a Web
page is hit, CounterBean will be invoked and will display the current
number of times users have visited the page.

1. From your home directory, change directory to mod9-beans/lab.

2. Open the CounterBean.java file using text editor.

3. The CounterBean.java servlet file contains a few comments and


a declaration for the CounterBean class. Insert code within
CounterBean.java to do the following:

▼ Track the number of hits through the declaration of a count


variable (supplied).

▼ Get and set the value for count by creating get and set
accessor and mutator methods.

▼ Add to count by creating an addCount accessor method.

▼ Calling the addCount method when the service method


receives a request.

▼ Return the current count as a response (supplied).

Note – A Web page counter should be invoked every time a Web page
is visited (not when a Web page action is performed). The
CounterBean.java file overrides the standard Servlet.service
method. This is because other HTTP-based service methods (such as
doPost and doGet) require action, on behalf of the Web browser user,
to invoke the servlet.

✓ Students can use GenericServlet for this exercise.

9-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Creating the CounterBean Servlet Bean (Continued)

4. Compile your CounterBean.java file to create a


CounterBean.class file.

5. Create a JAR file that includes your CounterBean.class and a


manifest file:
% jar -cvf CounterBean.jar CounterBean.class

Note – The manifest file will be created automatically.

6. Copy the JAR file to the server_root/servletbeans directory.

Servlet Beans 9-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Testing the CounterBean Servlet Bean

1. Add the CounterBean to Java Web Server. Refer to Appendix B,


“Using Java Web Server,” for more information.

2. Click on the Properties tab to display the Properties card. You


should see two properties listed: servletInfo and count.

3. Type a new value in the Count Property field. Press the Return key
once you are finished.

4. Click on Save to save the count value as the default value for the
CounterBean servlet Bean. Java Web Server will create a
CounterBean.ser file, containing this value, in the
server_root/servletbeans directory.
✓ Mention that Bean configuration can be done differently on another Web server.

5. Copy the CounterBean.shtml page to the


server_root/public_html directory.

6. Invoke CounterBean by accessing the .shtml page using your


Web browser:
http://host_name:8080/BeanCounter.shtml

7. The CounterBean should increment each time you reload the


.shtml file.

Note – Remember, the CounterBean is not saving its state each time it
is accessed. In the next exercise you will implement the code necessary
to save CounterBean’s state (the current count).

✓ Appendix B contains a section on server-side includes. Students are encouraged to read


this section if they want to understand this Java Web Server feature.

9-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Implementing Servlet Bean Persistence

1. Modify your CounterBean.java file. The CounterBean servlet


Bean should now contain the following:

▼ A variable pointing to the exact location of your serialized file.


For example:
String serFile =
"/opt/JavaWebServer/servletbeans/BeanCounter.ser";

▼ The code necessary to write the count to the serialized form of


the CounterBean servlet Bean. This code should allow the
counter’s state to be saved in the event the CounterBean servlet
Bean is removed or the Web server is shut down. Remember to
implement the java.io.Serializable interface within your
servlet’s class declaration.
✓ Students can write the Bean from within destroy. They can also write state as the counter
increments. The Bean’s state will be read automatically by Java Web Server when the
servlet Bean is reloaded.

✓ Ask students what the benefits of writing to the .ser in service versus destroy are. If
there is a power failure, the Bean’s state is more likely to be written if it is done in
service, destroy might never be called in this case.

2. Recompile your CounterBean.java file to create a


CounterBean.class file.

3. Create a new JAR file that includes your new CounterBean.class


and a manifest file:
% jar -cvf CounterBean.jar CounterBean.class

4. Copy the JAR file to the server_root/servletbeans directory.

5. Invoke CounterBean by accessing the .shtml page using your


Web browser:
http://host_name:8080/CounterBean.shtml

Servlet Beans 9-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Implementing Servlet Bean Persistence (Continued)

6. The CounterBean should increment each time you reload the


.shtml file.

▼ Before continuing with the next step, note the number of hits
that the CounterBean is displaying.
✓ Students need to remember the number of hits to verify that their serialization code is
working correctly.

7. Highlight the Web Service and click on the Shutdown button to


shut down the entire Web server and unload the CounterBean
servlet.
✓ Restarting the Web server does not unload servlet Beans.

✓ Restart Java Web Server from the server_root/bin directory:


./httpd &
✓ Java Web Server may not restart because it did not release the ports used by the
Adminstration Tool. If this occurs, restart Windows 95 entirely.

8. Wait approximately one minute for the Java Web Server to reload.

9. Invoke CounterBean by accessing the .shtml page using your Web


browser:
http://host_name:8080/CounterBean.shtml

▼ If your serialization code is working correctly, the


CounterBean should contain a value that is greater than the
value noted in step 6.
✓ Remember, each time the counter servlet is accessed, it increments. So, when you access
it for the first time after it has serialized itself, the counter will have added one to the
serialized value.

9-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Tasks

Creating an Advanced Counter Servlet Bean

1. Create a servlet that keeps track of the total number of hits, for a
Web page. This counter should keep individual numbers of hits
for each Internet Protocol (IP) address accessing the page.

Servlet Beans 9-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Exercise: Creating a Servlet Bean

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You might want
to go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.

9-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Define the terms JavaBeans, Bean, and servlet Bean

❑ List the four types of functionality most Beans provide

❑ Explain the two ways to pass properties to servlet Beans

❑ Describe how to package and install servlet Beans

❑ List the three ways of invoking servlet Beans

❑ Develop a servlet Bean

❑ Invoke a servlet Bean using Java Web Server and an .shtml Web
page

Servlet Beans 9-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
9
Think Beyond

How might you use the JavaBeans event mechanism to extend the
functionality of your servlet Beans?

9-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Dynamic Web Content 10

Course Map
This module discusses JavaServer Pages, an integrated solution for
generating and returning dynamic Web page content to a client
(browser).
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets

Servlet Life Cycle

Distributed Servlets

Database RMI and


Access CORBA/IDL

Collaborative Servlets

Persistent State in Time Extended


HTTP Servlets Connections

Servlet Security
Servlet
Security

Servlet Hybrids

Servlet Dynamic Web


Beans Content
Balanced Solutions

10-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following question is relevant in understanding the


topics presented in this module.

The term dynamic content refers to the ability of server-side software,


such as a servlet, to create and return HTML pages on-the-fly to a
client. What are some of the uses you can think of for dynamic Web
page creation?
✓ A servlet may respond to a client query by creating a Web page containing a table of data
stored in a database.

✓ A servlet may return an HTML page upon receiving and parsing a completed HTML form.

10-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Objectives

Upon completion of this module, you should be able to

● List three ways of generating dynamic Web page content

● Identify the methods used for generating dynamic HTML from a


servlet

● Describe the use of the PageCompileServlet

● Explain the two primary benefits of JavaServer Pages

● List the five directives that can be used within a JavaServer page

● Create a simple JavaServer page

● Use a Bean with a JavaServer page

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaServer Pages. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1.1/jsp.html.

● Introducing Page Compilation. [Online]. Available:


http://jserv.javasoft.com/products/java-server/
documentation/webserver1.1.1/page_comp/intro.html.

Dynamic Web Content 10-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Generating Dynamic Content

There are three primary ways to generate dynamic content:

● CGI script print statements

● Servlet println statements

● JavaServer Pages (JSP)


✓ JavaScript has also been a popular solution.

10-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

CGI print Statements

As mentioned in Module 1, CGI scripts can return HTML within a


response through the use of scripting language commands, such as
Perl’s print command, in the script’s response code. For example, the
following code uses the Perl print command to print the string “Hello
World” through standard output:
24 print "<HTML><HEAD><TITLE>Hello World</TITLE>
</HEAD><BODY><h1>Hello World</h1></BODY></HTML>";

Dynamic Web Content 10-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Servlet println Statements

As shown in Module 1, servlets can return HTML within a response


through the use of println statements in the servlet’s response code.
The information returned can be as simple as a string or as complex as
a table of data gathered from a database. For example, the code to
obtain a person’s name from a form and return it as part of a string
within a new HTML page might be

out.println("<HEAD><TITLE>Howdy Servlet</TITLE></HEAD>");
out.println("<BODY>");
out.println("Howdy " + getParameter("yourname"));
out.println("</BODY>");
out.close();

Note – Several sample servlets are included with this course’s


materials. DBServlet.java, located in mod10-dynamic/examples/,
demonstrates how to create a table of data from a database
dynamically.

10-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Servlet println and Perl print Statements

Two shortcomings resulting from using println and Perl print


statements in a servlet and CGI script, respectively are:

● These statements force you to combine HTML and code for the
Java platform (“Java code”) or script code within your servlets,
preventing reuse of code.

● It forces HTML experts to understand particulars of Java


technology (for servlets) or Perl code (CGI scripts) used for
content generation, and developers of Perl or Java technology to
deal with HTML content layout and presentation (two distinct
jobs).

Dynamic Web Content 10-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

JavaServer Pages

Definition
JavaServer Pages (JSP) are Web pages that contain a combination of
HTML and code written in a scripting language such as the Java
programming language. The two primary benefits of JavaServer Pages
are:

● They cleanly separate page presentation from page content in


dynamically generated pages by letting you call objects for the
Java platform (“Java objects”) from within a JavaServer page.

● They are automatically recompiled by the PageCompileServlet


when changes are made to the source file.
✓ A customer might ask about the difference between JSP and Java HyperText Markup
Language. JSP pages were introduced as part of Java Web Server 1.1.1 and are a
predecessor to JHTML. JavaServer Pages is backward-compatible with JHTML.

✓ As of May, 1998, the Java programming language was the only language supported by
JSP.

10-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
JavaServer Pages

Definition
JavaServer Pages are processed by a special servlet called the
PageCompileServlet.
✓ There is some debate on the usefulness of JavaServer pages because, as with the println
method, they also combine scripting (Java) code with HTML. If a student presents this
argument, reiterate that the separation of HTML and scripting code is accomplished
through a special Beans tag (which is discussed later).

✓ Additionally, JavaServer Pages are a great way to create a quick servlet-based solution
without having to be aware of class loader or classpath configuration.

✓ Important–Java Server Pages is a new technology that has not been made available in a
final release of Java Web Server. Information on this module will not be complete until the
next official release of the Java Web Server product. Therefore, you should notify your
class that they are working with pre-released software and getting a preview of an
upcoming technology.

✓ While Java Server Pages is specific to Java Web Server, similar technologies exist on
other Web servers. This information is provided to give students an idea of this type of
technology.

Dynamic Web Content 10-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
JavaServer Pages

An Example JavaServer Page


The code shown here demonstrates a simple JSP page that displays a
form, parses the form data, and returns the name to the Web browser.
1 <HTML>
2 <BODY>
3 <H1>GridConfig</H1>
4 <%
5 if (request.getParameter("first") == null) { %>
6 <FORM action="tst.jsp" method="post">
7 <P>
8 First Name
9 <P>
10 <INPUT type="text" name="first">
11 <INPUT type=submit value="submit">
12 <INPUT type=reset>
13 </FORM>
14 <%@ import = "java.lang.*" %>
15 <%} else {
16 if (request.getParameter("first").equals("")) { %>
17 <p>
18 You MUST fill in each field before submitting the form: Press the
Back button and fill in the empty fields in your form.
19 <%} else {
20 String foo = request.getParameter("first");
21 out.println(foo);%>
22 <%}
23 } %>

Note – The mod10-dynamic/examples/ directory contains a copy of


the jspform.jsp JavaServer Page source file.

10-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

JavaServer Pages Syntax

In addition to HTML, a JavaServer page can contain five types of


information:

● Directives

● Declarations

● Scriptlets

● Expressions

● Bean tags

Dynamic Web Content 10-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Directives

Directives enable you to modify certain characteristics of the JavaServer


page and resulting servlet. These specifics include the scripting
language and the packages used.

Language
The language variable is used to define the scripting language used in
a JavaServer page. The value of this tag applies to the entire file. If you
include the language tag more than once, only the value for the first
tag is used. If you omit this tag entirely, the scripting language defaults
to java.

<%@ language = "java" %>

Note – Java Web Server 1.1.1 supports only the Java programming
language for scripting. Other vendors might support other scripting
languages (for example, IBM supports REXX within their JavaServer
Pages equivalent).

10-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Directives

Method
The method variable is used to define the name of the method that will
contain the body of code generated from the JavaServer page. By
default, this method is the service method. The value for this tag
applies to the entire file. If you include the method tag more than once,
only the value for the first tag is used. For example, to change the
default method to doPost, your JavaServer page would contain

<%@ method = "doPost" %>


✓ You can use this variable to define a doPost or doGet to pick up HTTP OPTIONS, HEAD, or
TRACE support.

Import
The import variable is used to define the list of package names or
class names, each separated by a comma, that will be imported by the
generated servlet. You can use this tag multiple times within a file. For
example, to import the java.io.* and java.util.Hashtable
packages, your JavaServer page would contain:
<%@ import = "java.io.*,java.util.Hashtable" %>

The example uses the import statement to import the java.lang


package (line 14).

Implements
The implements variable is used to define the list of interface names,
each separated by a comma, that the generated servlet implements.
You can use this tag multiple times within a file.

<%@ implements = "SingleThreadModel" %>

Dynamic Web Content 10-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Directives

Extends
The extends variable is used to define the name of the super class that
the generated servlet extends. The value for this tag applies to the
entire file. If you include the method tag more than once, only the
value for the first tag is used. For example, if the servlet generated
from your JavaServer page extended HttpServlet, your JavaServer
page would contain
<%@ extends = "javax.servlet.http.HttpServlet" %>

10-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Declarations

Definition
Declarations identify class-wide variables and methods used by the
generated servlet. Variable and method declarations are defined within
starting and ending SCRIPT tags. The starting SCRIPT tag is

<SCRIPT runat=server>

The ending SCRIPT tag is

</SCRIPT>

The runat=server tag is required and indicates that the contents


within the SCRIPT tag are for server-side processing, not for the client
or browser.

Dynamic Web Content 10-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Declarations

An Example JavaServer Page Declaration


Following are variable declarations within the bounds of the SCRIPT
tag:

< SCRIPT runat=server >


int i = 0;
String foo = "Hello";
private void foo() {
// some code;
}
< /SCRIPT >

10-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Scriptlets

Definition
A scriptlet is the portion of scripting code used to add additional
functionality to the HTML within a JavaServer Page. You can use any
valid Java code within a scriptlet. Scriptlet code is defined within <%
and %> tags. The example has several examples of scriptlet code. Prior
to parsing the form request, a small portion of scriptlet code
determines whether or not the form has been completed (lines 4 and
5):
<%
if (request.getParameter("first") == null) { %>

Dynamic Web Content 10-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Scriptlets

Definition (Continued)
Additionally, the generated servlet will have access to several
predefined variables that reference objects common to most servlets
(such as a HttpServletRequest and HttpServletResponse). These
variables are: request, response, out, and in.

request
The request variable references an incoming
javax.servlet.http.HttpServletRequest object.

response
The response variable references a
javax.servlet.http.HttpServletResponse which is used for
outgoing responses.

out
The out variable references a java.io.PrintWriter output writer.
The example uses the request.getParameter method to parse the
request and then prints a response using the out.println method. A
small portion of scriptlet code determines whether the form has been
completed (lines 20–24):
<%} else {
String foo = request.getParameter("first");
out.println(foo);
}
} %>

in
The in variable references the java.io.BufferedReader input
reader.

10-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Expressions

Definition
Expressions are a type of tag that contain script language expressions
that are replaced with the values for those expressions, once an
expression has been resolved. Expressions are defined within <%= and
%> tags. An expression is evaluated to a result which is then
converted into a string and displayed. Conversions to string
representation for all primitive types, such as int and float, occur
automatically.

An Example JavaServer Page Expression


For example, suppose you want to display the result of a computation,
carried out in a block of scriptlet code, from within your HTML:
<% int number = 20;
int i = number + 1; %>
<p>
The result of the computation is:<% =i %>

Dynamic Web Content 10-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Additional Guidelines

Following are some additional guidelines for writing your JavaServer


pages:

● You can have many scriptlet blocks in a JavaServer page, each


mixed with HTML.

PageCompileServlet will ensure that each block is inserted into the


proper place within the resulting servlet.

● If you declare a variable in one scriptlet block, that variable will be


“visible” in subsequent scriptlet blocks.

You cannot reuse a variable name later in your page. If you need
to use the same variable name twice, use the scoping syntax of
your scripting language to establish a scope for each variable. For
example, in the Java programming language, you would use
braces to establish scope for a series of methods and variables.

10-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Additional Guidelines

● You can use conditional statements to determine whether a block


of HTML should be printed. For example:
<% if (balance >= 100.00) { %>
<p>You use the phone far too much!
<% } %>

In the example shown, if the value for the balance variable is more
than 100.00, the message You use the phone far too much! is
printed.
✓ One important use of conditionals in JSP is to ensure that an HTML form is filled in prior
to extracting the form’s data using the request variable. You can use an if/else statement
to check if the form has been filled in (right before the FORM tag), and if so, continue to
process the form’s parameters.

You can use println statements, within your scriptlet code, to


send HTML to an output buffer.

Dynamic Web Content 10-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

The <BEAN> Tag

Definition
One of the most powerful and important features of JavaServer Pages
is the ability to access any Java object from within a JavaServer page.
This feature enables you to completely separate HTML presentation
from Java programming language content creation.
✓ It is important to repeat that you can use the BEAN tag to reference any Java object. The
comparable tag in Active Server Pages by Microsoft, is OBJECT.

10-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
The <BEAN> Tag

An Example JavaServer Page Using the <BEAN> Tag


1 <html>
2
3 <!-- jsp.beans.ColorGameBean MUST be CLASSPATH -->
4 <!-- by default in our distribution it is found in the classes/
subdirectory -->
5
6 <%@ import="jsp.beans.ColorGameBean" %>
7
8 <bean name="cb" class="jsp.beans.ColorGameBean" create="yes"
scope="session" introspect="yes"></bean>
9
10 <body bgcolor= <%= cb.getColor1() %>>
11 <font color=<%= cb.getColor2() %>>
12 <p>
13
14 This Web page is an example using JSP and BEANs.
15 <p>
16 Guess my favorite two colors
17
18 <p> If you fail to guess both of them - you get yellow on red.
19
20 <p> If you guess one of them right, either your foreground or
21 your background will change to the color that was guessed right.
22
23 <p> Guess them both right and your browser foreground/background
24 will change to my two favorite colors to display this page.
25
26 <% if (cb.getHint()) { %>
27
28 <p> Hint #1: Vampires prey at night!
29 <p> Hint #2: Nancy without the n.
30
31 <% } %>
32
33 <% if (cb.getSuccess()) { %>
34 <% cb.reset(); %>
35

Dynamic Web Content 10-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
The <BEAN> Tag

An Example JavaServer Page Using the <BEAN> Tag


(Continued)
36 <p> CONGRATULATIONS!!
37 <p> You guessed in <%= cb.getAttempts() %> attempts!
38
39 <% if (cb.gotHints()) { %>
40
41 <p> ( although I know you looked at the hints)
42 <% } %>
43 <% } else { %>
44
45 <p> Total attempts so far: <%= cb.getAttempts() %>
46 <p>
47
48 <form method=POST action=/colors.jsp>
49 Color #1: <input type=text name= color1 size=16
value="<%=cb.getColor1()%>">
50 <br>
51 Color #2: <input type=text name= color2 size=16
value="<%=cb.getColor2()%>">
52 <p>
53 <input type=submit name=action value="Submit">
54 <input type=submit name=action value="Hint">
55 </form>
56
57 <% } %>
58
59 <p>
60
61 </font>
62 </body>
63 </html>

10-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Declaring a Bean

In the previous example, the ColorBeanGame Bean is defined using


the <BEAN> tag (line 8). Bean and object declarations are placed
between the <BEAN> and optional </BEAN> tags. The BEAN tag uses the
following syntax:
< BEAN name="value" varname="value" class="name"
introspect="no"
serializedfile="value" create="no" scope="request">

name
The example sets name to cb. The name attribute identifies the key
used to look up the Bean or object in the appropriate scope. For
example, name may refer to a session key value where the Bean is
stored. In example shown here, the Bean name is myBean.
✓ Use a unique name for every Bean in every JavaServer page you create. Using the same
name for Beans in different JavaServer pages can cause a conflict.

Dynamic Web Content 10-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Declaring a Bean

varname
The varname attribute identifies a variable name that can be used to
refer to the Bean in other portions of the JavaServer page. The example
uses the varname to reference an accessor method in the
ColorGameBean (lines 10, 11, 33, 34, 39, 49, and 51) of the example
code. For example:
<body bgcolor= <%= cb.getColor1() %>>

The varname is an optional attribute. If varname is not specified, the


name of the variable defaults to the name of the Bean specified by the
name attribute.

type
In the example, type is equal to ColorGameBean.The type attribute
identifies the name or interface of the Bean’s class file. If a class is not
specified, it defaults to the type Object.

introspect
In the example, introspect is equal to yes. The introspect attribute
identifies whether the Bean’s set acessor methods are called when an
associated property is handed to the Bean within the request. The
instrospect attribute can be set to either yes or no.

Note – By declaring a BEAN tag, the JavaServer page will have access to
a Bean whose properties have been set to the values of the parameters
(query parameters or posted form parameters) that the client called the
page with.

10-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Declaring a Bean

create
In the example, create is equal to yes. The create attribute identifies
whether or not to create the Bean if it is not found in the specified
request or session. The create attribute can be set to either yes or no.
The default value of create is yes.

scope
In the example, scope is equal to session. The scope attribute is
used to identify where the Bean is retrieved from. Remember:

● A Bean can be created from a serialized file or a class file.

● A Bean can be referred to from an HTTP session.

● A Bean can be passed to the page from a servlet.

Dynamic Web Content 10-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Declaring a Bean

scope (Continued)
Once created, a Bean is alive for either the lifetime of the current
request or the lifetime of the session (depending on what the scope in
the BEAN tag is).

The scope attribute can be one of the following values:

request

If this value is used, the Bean is retrieved from the service’s request
context. This is the default value used when scope is not specified. If
the Bean is not part of the request context, then the Bean is created and
stored in the request context unless the create attribute is no.

session

If this value is used, the Bean is reused from the current session if
present. If not present, it is created and stored as part of the session if
the create attribute is yes.

The scope attribute is optional. If it is not specified, it defaults to the


request scope.
✓ Sessions were discussed in Module 6.

beanName
The beanName attribute identifies the name of the serialized file or
class that contains the Bean. This attribute is used only when the Bean
is not present in the scope of the <BEAN> tag and the value of the
create attribute is yes.
✓ Sessions were discussed in Module 6.

10-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

PageCompileServlet

The PageCompileServlet is invoked when a client requests a


JavaServer page. The PageCompileServlet is loaded and initialized like
any other servlet. The PageCompileServlet compiles JSP files into
servlets when the JavaServer pages are initially requested.

Dynamic Web Content 10-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
PageCompileServlet

Figure 10-1 depicts the conversion of a JavaServer page to a servlet


class.

Figure 10-1 JavaServer Page to Servlet Conversion

PageCompileServlet does all of its work on the server. A Web browser


references only the output of the servlet, not the servlet code.

The PageCompileServlet will recompile the JavaServer page if it


detects any changes to a JavaServer page after its initial compilation. If
the requested file does not change, PageCompileServlet uses the
existing servlet to handle a page request.

10-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
PageCompileServlet

An Example JavaServer Page


Following is an example of a simple JavaServer page:

1 <html><head><title>My First Page</title></head><body>


2 <h1>My First Page</h1>
3 <ul>
4 <%
5 for (int i = 0; i < 5; i++) out.println ("<li>" + i);
6 %>
7 </ul>
8 </body>
9 </html>

The scriptlet portion of the page lies between the <% and %> tags.

The first thing PageCompileServlet does with basicpage.jsp is


convert it to pure Java servlet definitions. The resulting code closely
resembles the following example:

Dynamic Web Content 10-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
PageCompileServlet

An Example Servlet Created From a JavaServer Page


1 package pagecompile;
2
3 import com.sun.server.webserver.pagecompile.filecache.*;
4 import com.sun.server.webserver.pagecompile.ParamsHttpServletRequest;
5 import com.sun.server.webserver.pagecompile.*;
6 import java.io.*;
7 import java.util.*;
8 import javax.servlet.*;
9 import javax.servlet.http.*
10
11 public class _FirstPage
12 extends HttpServlet{
13
14 //-------------------------------
15 static {
16 }
17
18 //-------------- The service method
19 public void service (HttpServletRequest request,
20 HttpServletResponse response) throws ServletException,IOException {
21 ServletOutputStream out = response.getOutputStream ();
22 ByteFileData __fileData = null;
23
24 try {

10-32 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
PageCompileServlet

An Example of a Servlet Created rom a JavaServer Page


(Continued)
25 __fileData = (ByteFileData)
26 ServletUtil.getFileCache(this).getFile(
"C:\\Java Web Server1.0\\public_html\\FirstPage.jhtml",
null, 865872648000L);
27 if (__fileData == null) throw new
28 ServletException("FileChanged");
29
30 /*** lines: 1-3 */
31 __fileData.writeBytes (0, 93, out);
32
33 for (int i = 0; i < 5; i++) out.println ("<li>" + i);
34
35 /*** lines: 5-8 */
36 __fileData.writeBytes (175, 40, out);
37 } finally {
38 if (__fileData != null) __fileData.close();
39 }
40 }
41 }

Dynamic Web Content 10-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

PageCompileServlet

Creating a Servlet From a JavaServer Page


In the previous example, PageCompileServlet places JavaServer page
scriptlet code and HTML code within the servlet’s service routine (or
in the service method you define using the method variable). HTML is
directly written to a stream to be displayed on the client (lines 31 and
36). Scriptlet code appears unmodified within the service routine (line
33).

Notice that PageCompileServlet creates ServletOutputStream called


out (line 21). The servlet uses this stream to print the initial 93 bytes of
pure HTML. Then, the for statement executes and the remaining 40
bytes of HTML are sent to the output stream.

Note – The basicpage.jsp JavaServer page is included with this


course’s materials in mod10-dynamic/examples. You can access
basicpage.jsp by copying it to server_root/public_html and
typing HTTP://host_name:8080/basicpage.jsp within your Web
browser.

10-34 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Review of JavaServer Pages

JavaServer pages allow a combination of HTML and scripting code to


interoperate within a special .jsp Web page. JavaServer pages are
compiled on the fly when they are invoked by a Web browser:

● JavaServer pages consist of directives, declarations, scriptlets,


expressions, and BEAN tags.

● Directives enable you to modify certain characteristics of the


JavaServer page and resulting servlet.

▼ language is used to define the name of the scripting language


used.
▼ method is used to define the name of the service method you
want the resulting servlet to override.
▼ import is used to define the import libraries for the scripting
language.
▼ implements is used to define any interfaces implemented by
the resulting servlet.
▼ extends is used to define any classes that the resulting servlet
extends.

Dynamic Web Content 10-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Review of JavaServer Pages

● Declarations identify class-wide variables and methods used by


the generated servlet.

● A scriptlet is the portion of scripting code used to add additional


functionality to the HTML within a JavaServer page.

▼ Scriptlets are placed between <% and %> tags.

● Expressions are a type of tag that contains script language


expressions that are replaced with the values for those expressions,
once an expression has been resolved.

▼ Expressions are placed between <%= and %> tags.

10-36 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10

Review of JavaServer Pages

● The <BEAN> tags enables the system to access any Java object from
within a JavaServer page.

● Bean and object declarations are placed between the <BEAN> and
optional </BEAN> tags.

▼ The name attribute identifies the key used to look up the Bean
or object in the appropriate scope.
▼ The varname attribute identifies a variable name that can be
used to refer to the Bean in other portions of the JavaServer
page.

▼ The type attribute identifies the name or interface of the


Bean’s class file.

▼ The introspect attribute determines whether the Bean’s set


acessor methods are called when an associated property is
handed to the Bean within the request.

▼ The create attribute determines whether to create the Bean if


it is not found in the specified request or session.

Dynamic Web Content 10-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Review of JavaServer Pages

▼ The scope attribute is used to identify where the Bean is


retrieved from (the request or session context).

▼ The beanName attribute identifies the name of the serialized file


or class that contains the Bean.

● The PageCompileServlet is invoked when a client requests a


JavaServer page.

● The PageCompileServlet compiles JSP files into servlets when the


JavaServer pages are initially requested.

10-38 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Exercise objective – Create a simple JavaServer page that requests


form data, submits the data, computes two values from the data, and
displays the computed values. Create an JavaServer page that sends
the computed values to an ImageTableBean to display a user-definable
grid of images on a Web page.

Preparation
● The Java Web Server must be installed and running on your
system. Refer to Appendix B, “Using Java Web Server,” for more
information regarding Java Web Server installation, execution, and
documentation.

● Refer to http://host_name:8080/system/doc/index.html
for help with the servlet API.

● Copy the contents of mod10-dynamic/lab/jsp/beans to


server_root/classes/jsp/beans/.

● Copy the mod10-dynamic/images/ directory to


server_root/public_html/.

Dynamic Web Content 10-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Developing the ImageTableInfo.jsp JavaServer Page

The ImageTableInfo.jsp JavaServer page is a form/scripting


language combination that accepts information for an image grid: a
grid of square images that update at a defined interval.
ImageTableInfo accepts this information, calculates the height and
width of an image grid, and returns the calculated values.
✓ In the second exercise, students will take the calculated values and pass them to a Bean
that will display the grid on the client.

A form with the following fields is provided within a JSP file:

● Duration images will be displayed before updating

● Number of images horizontally

● Number of images vertically

● Height of each image in pixels

● Width of each image in pixels

1. Create Java code, within this same JavaServer page, to parse form
fields as request data.
✓ Students might use request.getParameter(“parametername”) to get each parameter (after
the form has been submitted). Parameters will be passed as strings, so students will have
to convert them to ints, and perform necessary calculations.

✓ Students may have trouble understanding how to have parameters be parsed only after
the form has been submitted. The trick is to use an if/else combination before the HTML
form: verify that fields are empty; if they are empty display the form; otherwise parse the
parameters.

10-40 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Developing the ImageTableInfo.jsp JavaServer Page


(Continued)

2. Create Java code, within this same JavaServer page, to calculate


the total width and height of an entire grid of images. The
formulas are:

width = (number of horizontal squares * width of


image in pixels) + number of horizontal squares +
1

height = (number of vertical squares * height of


image in pixels) + number of vertical squares + 1

3. Create the Java code, within this same JavaServer page, to return
and display the width and height of the entire grid of images.
✓ It is not necessary to use out.println to return the results (although this should work).
Any HTML text you print after the submittal of the form will automatically be printed on a
separate HTML page. For example, the solution uses a form within a table. Once the form
is submitted, the parameters are parsed, the calculations are made, and a new table
containing the results is created (in HTML), which contains <%=width%> or <%=height%>
scriptlets, embedded within the HTML, to display the calculated values.

✓ Students may want to return all of the data.

4. Save your ImageTableInfo JavaServer page and copy the page to


servlet_root/public_html.

5. Invoke your JavaServer page directly, using a Web browser:


http://host_name:8080/ImageTableInfo.jsp

Dynamic Web Content 10-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Developing the ImageTableInfo.jsp JavaServer Page


(Continued)

6. Enter the following into each field and click Submit:

▼ Duration: 10

▼ Images horizontally: 5

▼ Images vertically: 5

▼ Width in pixels: 20

▼ Height in pixels: 20

The Web browser should display the values computed within your
JavaServer page. If you used these values, the returned values
should be:

▼ Total width: 106

▼ Total height: 106


✓ Make sure students remember to include the .jsp extension required to notify the
PageCompile servlet that this is a JavaServer page.

10-42 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Calling the ImageTableBean from the ImageTable.jsp JavaServer


Page

ImageTableBean is used for displaying a user-defined grid of images


on a Web page. In this exercise, you will modify the ImageTable.jsp
page to call the ImageTableBean and pass it the form parameters
needed to display the grid of images.

The ImageTable.jsp file accepts the same five values listed in the first
task: duration, vertical images, horizontal images, vertical pixels, and
horizontal pixels. The following steps should occur, within
ImageTable.jsp, after this information is submitted using the form
portion of ImageTable.jsp:

● The <BEAN> tag is used to define the Bean used in the JSP page.

● The form values are parsed and held by their respective variables.
This includes a startImage variable that is not entered in the
form, but keeps track of the starting image for the grid of images
(provided).

● The values are passed to the Bean by calling the various set
accessor methods within the Bean. These methods are documented
within the mod10-dynamic/lab/doc/
jsp.beans.ImageTableBean.html Javadoc file.

● The table is generated by calling an additional generateTable


API within the Bean.

The following steps occur within ImageTableBean once


generateTable is called:

● A circular queue (Vector) of image names is created.

● An output string is created to hold the output.

Dynamic Web Content 10-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Calling the ImageTableBean from the ImageTable.jsp JavaServer


Page (Continued)

● The output contains HTML containing the form values and grid of
images). The form’s values are placed within a special META tag:
<META HTTP-EQUIV=REFRESH CONTENT="DURATION;
URL=http://...">
● This tag tells the Web browser to refresh its image grid with new
copy based on the time indicated by the DURATION value. The
supplied URL is used to specify the parameters for the image grid.
This mechanism is known as a client pull mechanism as the client
will pull updated information from the Web server.

Note – The ImageTableBean.java source file is located in the


mod10-dynamic/lab/ directory.

1. Modify the ImageTable.jsp page. Make the following changes:

▼ Use the <BEAN> tag for the ImageTableBean to the beginning


of ImageTable.jsp.

▼ Make the necessary calls, within the Bean, to configure values


for the ImageTableBean and generate a table of images.
Remember to call the accessor method for the startImage
value.

Note – Refer to the additional setup notes at the beginning of this


exercise for setting up the ImageTable classes and image files.

2. Save your ImageTable JSP page and copy the page to


server_root/public_html.

10-44 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Tasks

Calling the ImageTableBean from the ImageTable.jsp


JavaServer Page (Continued)

3. Invoke your JavaServer page directly, using a Web browser:


http://host_name:8080/ImageTable.jsp

4. Enter the following into each field and click Submit:

▼ Duration: 10

▼ Images horizontally: 5

▼ Images vertically: 5

▼ Width in pixels: 20

▼ Height in pixels: 20

The Web browser should display a grid of 25 images (5 by 5) that


updates every 10 seconds.

Dynamic Web Content 10-45


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Exercise: Creating JavaServer Pages

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion., then just highlight the key concepts students should have learned from the
lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations back at their workplace.

10-46 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Check Your Progress

Before continuing, check that you are able to accomplish or answer the
following:

❑ List three ways of generating dynamic Web page content

❑ Identify the methods used for generating dynamic HTML from a


servlet

❑ Describe the use of the PageCompilationServlet

❑ Explain the two primary benefits of JavaServer Pages

❑ List the five directives that can be used within a JavaServer page

❑ Create a simple JavaServer page

❑ Use a Bean with a JavaServer page

Dynamic Web Content 10-47


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
10
Think Beyond

How might you use JavaServer Pages on your Web site?

10-48 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
CGI, HTTP, and Servlets A
This appendix lists additional information about the HTTP protocol.

A-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
A
HTTP MIME Types

Multipurpose Internet mail extension (MIME) types are used to


differentiate different types of data sent over the Web via HTTP.
Table A-1 lists all of the different MIME types.
Table A-1 MIME Types

MIME Type File Extension(s)


application/activemessage
application/andrew-inset
application/appletfile
application/atomicmail
application/dca-rft
application/dec-dex
application/mac-binhex40
applicatoin/macwriteii
application/msword
application/news-message-id
application/news-transmission
application/octet-stream bin
application/oda oda
applicatoin/pdf pdf
application/postscript ai eps ps
application/remote-printing
application/rtf rtf
application/slate
application/xmif mif
application/wita
application/wordperfect5.1
application/x-csh csh
application/x-dvi dv

A-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
A
MIME Type File Extension(s)
application/x-hdf hdf
application/x-latex latex
application/x-netcdf nc cdf
application/x-sh sh
application/x-tcl tcl
applicaiton/x-tex tex
application/x-texinfo texinfo texi
application/x-troff t tr roff
application/x-troff-man man
application/x-troff-me me
application/x-troff-ms ms
application/x-wais-source src
application/zip zip
application/x-bcpio bcpio
application/x-cpio cpio
application/x-gtar gtar
application/x-shar shar
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-tar tar
application/x-ustar ustar
audio/basic au snd
audio/x-aiff aif aiff aifc
audio/x-wav wav
image/gif gif
image/ief ief
image/jpeg jpeg jpg jpe
image/tiff tiff tif
image/x-cmu-raster ras

CGI, HTTP, and Servlets A-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
A
MIME Type File Extension(s)
image/x-portable-anymap pnm
image/xportable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/external-body
message/news
message/partial
message/rfc822
multipart/alternative
multipart/appledouble
multipart/digest
multipart/mixed
multipart/parallel
text/html html
text/plain txt
text/richtext rtx
text/tab-separated-values tsv
text/x-setext etx
video/mpeg mpeg mpg mpe
video/quicktime qt mov
video/x-msvideo avi
video/x-sgi-movie movie

A-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Using Java Web Server B
This appendix describes how to install, run, and log in to the Java Web
Server. References for servlet information are also presented in this
appendix.

B-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Supported Platforms

The Java Web Server is officially supported only under the Solaris™
SPARC™ and Windows NT environments. Windows 95 is supported
for development but is not recommended for deployment because
Microsoft does not consider it a server platform.

The Java Web Server runs on any platform that supports Java
Development Kit (JDK) 1.1 or above.

B-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Prerequisites

Hardware

Solaris

● The archive file is approximately 16 Mbytes.

● Your system will require roughly 22 Mbytes of hard drive space to


install Java Web Server.

Software
You must configure a server environment to run Java Web Server, and
a client environment to run the Web server administration tools.

Server Environment

You can use one of the following to execute Java Web Server:

● Java runtime environment (JRE) 1.1.4 provided with Java Web


Server

● JDK 1.1 (or above)-compliant JRE

Note – You will use the Java Web Server JRE to run Java Web Server
during this course.

✓ JRE included with Java Web Server was used to keep things simple. Students can read
the on-line Java Web Server documentation, to see how to use an alternative JRE.

Using Java Web Server B-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Prerequisites

Software

Client Environment

You must have the following item for your client environment:

● A Web browser compatible with JDK 1.0.2 or above

Note – Most browsers are JDK 1.0.2-compatible. Current versions of


Netscape Navigator (3.0, 4.0), Microsoft Internet Explorer (3.0), and
AppletViewer (1.0.2, 1.1) are known to be compatible with Java Web
Server. This course contains a copy of Netscape Navigator 4.02.

B-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Installation

The lab files for this course include a copy of Java Web Server. This
product will be installed by your instructor prior to the course.
However, the Java Web Server installation instructions are included
here for future reference.

Solaris
1. Copy the jws111-solaris.tar.Z file from the SL310_LF
directory to a directory where you want Java Web Server installed.

2. From the JavaWebServer directory, type:

zcat jws111-solaris.tar.Z | tar -xvf -

3. Press Return to begin installing Java Web Server. The archive file
will create a JavaWebServer directory within the same directory
where the archive file exists.

Note – The JavaWebServer directory is referred to as server_root


within this course. The JSERV_HOME environment variable is used to
point to server_root.

✓ As of the alpha release of this course, JavaServer Pages was only available as a trial
version of Java Web Server. Additionally, there is a 1.1.1 update that fixes some bugs in
Java Web Server 1.1, but does not include JSP. A special Java Web Server 1.1.1 (with JSP)
version is used for this course.

Using Java Web Server B-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Running the Java Web Server

Solaris
1. Set JSERV_HOME to server_root: the location where the Java
Web Server is installed.

2. Set the CLASSPATH variable to include


$JSERV_HOME/lib/jsdk.jar, $JSERV_HOME/lib/x509v1.jar,
and . (for the current directory).

3. From server_root, change directory to bin.

% cd server_root/bin

4. Invoke the server process (daemon).

% ./httpd &

5. Verify that the server process is running using the ps -ef


command:
ps -ef | grep httpd

B-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Displaying the Default Home Page

After you have started the server, you can display the default Java
Web Server home page by entering the following URL in your Web
browser:

http://host_name:8080/

For example, if your machine is named galaxy, enter


http://galaxy:8080.

Using Java Web Server B-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Launching the Administration Applet

To invoke the Java Web Server Administration applet:

1. From the default home page on port 8080, click on the link labeled
Administration Tool.

2. From the JavaServer Administration page, click on the link labeled


Start the Administration Tool.

Note – You can also connect to the Administration Tool by typing its
URL. For example, if the host name for your Java Web Server is bagua,
then you enter the URL http://bagua:9090/index.html.

3. Log in using the default user name admin and the default
password admin. Figure B-1 shows the Administration Tool
window.

Figure B-1 The Administration Tool

Notice that the Web Service is highlighted and has a status of


Running.

You are now ready to add a servlet to Java Web Server.

B-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Adding a Servlet to Java Web Server

Once you have created a servlet, add it to the list of available servlets
within Java Web Server.

To add a servlet to Java Web Server:

1. Log in to the administration applet.

2. Highlight Web Service and click on the Manage button. A separate


Java Web Server Web Service screen will be displayed.

3. Click on the Servlets button. A hierarchical menu of servlets


(Figure B-2) will be displayed.

Figure B-2 Hierarchical Menu of Servlets

Using Java Web Server B-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Adding a Servlet to Java Web Server

4. Select Add from the hierarchical menu. The Add a New Servlet
screen will be displayed (Figure B-3).

Figure B-3 Add a New Servlet

5. Enter the unique name of the servlet in the Servlet Name field.

6. Enter the name of the Java class for the servlet. This consists of the
package name without the .class extension.

7. If your servlet is a servlet Bean, click on Yes within the Bean


Servlet field and then enter the name of the JAR file that contains
your servlet Bean.
✓ Remind students that servlet Beans are not introduced until Module 3 and that the
servlets created in Module 1 and 2 are not servlet Beans.

8. Click on the Add button. The servlet name that you assigned to
the servlet will appear in the hierarchical list under Configure.

B-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Adding a Servlet to Java Web Server

9. Click on the Add button to add a new property

10. Type resultsDir in the Property field.

11. Type server_root/servlets/ in the Value field.

12. Click on the Save button.

Using Java Web Server B-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Adding Initialization Parameters

Defining initialization parameters is server-specific. Java Web Server


has an initialization property (parameter) editor that enables you to
specify initialization parameters for each of the servlets you develop.

To configure the parameters for a servlet:

1. Log in to the administration applet.

2. Highlight Web Service and click on the Manage button. The Java
Web Server Web Service screen will be displayed.

3. Click on the Servlets button.

4. Select a servlet from the Configure list. Two configuration tabs will
display: Configure and Properties.

5. Click on the Properties tab (Figure B-4) to display the Properties


card.

Figure B-4 Servlet Initialization Property (Parameter) Editor

B-12 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Configuring a Remote Servlet

To configure a remote servlet using Java Web Server:

1. Add your servlet to Java Web Server. Adding servlets was covered
earlier in this appendix.
✓ The Java Web Server should have been installed prior to these instructions.

✓ All settings can be demonstrated by the instructor.

2. Click on the Configuration tab to display the Configuration card


(Figure B-5).

Figure B-5 The Configuration Card

Using Java Web Server B-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Configuring a Remote Servlet

3. Click on Yes within the Load Class Remotely section and then
enter the URL for the location of your remote servlet.

4. Click on Save to save your changes.


✓ See the security module for the security implications of remote servlets

✓ You can use server-side includes or filter chaining to invoke your remote servlets. These
features are discussed later in this module.

B-14 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Invoking a Servlet From Within an HTML Form

As with CGI, you can invoke a servlet upon submitting information


within an HTML form. The action parameter of the form tag is used to
define the name of the servlet to be invoked. The method parameter of
the form tag is used to define the HTTP method type. For example, to
invoke the CustomerForm servlet with an HTTP GET method, your
HTML form would use:
<form
action=http://host_name:port/servlet/servlet_class
method=http_method>

For example:
<form
action=http://fuggles:8080/servlet/CustomerForm
method=GET>

Using Java Web Server B-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Server-Side Includes (SSI)

Overview
Server-side includes (SSI) enables you to embed instructions to the
server inside an HTML document. The instructions are given using
extensions to the HTML tag language. A special file extension, .shtml,
signals the server that the document contains SSI directives. The server
parses the document, executing SSI code in-line. Results are embedded
in the document before it is served to the client.

Usage and Implications


Server-side includes can be as simple as embedding boilerplate text
(such as copyright notices) or as powerful as calling executable
programs (such as servlets). Traditionally, there have been two
considerations for Web administrators in allowing server-side
includes: security and performance. The security issue usually centers
around whether you want document providers issuing executables on
the server. The performance issue focuses on the impact of having a
heavily loaded server parsing documents prior to serving them.
✓ The security issues regarding server-side includes is in Module 8.

Standard Server-Side Include Tags


The National Center for Supercomputing Applications (NCSA) format
for SSI directives is an structured generalized markup language
(SGML)/HTML comment. If, for any reason, a document containing
SSI directives is served to the client unparsed, the comment format
indicates that the directive’s coding will not be visible. Directives have
the following format:
<--#command tag1="value1" -->

For example:
<!--This file: pressrelease.shtml-->

B-16 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Server-Side Includes (SSI)

Server-Side Include Tags for Servlets


The Java Web Server provides support for both standard and servlet-
specific SSI commands. The servlet-specific SSI commands provide a
convenient way to load and invoke servlets. Both local and remote
servlets can be used in this manner.

The syntax of an SSI tag for inclusion of servlets differs from the
NCSA syntax discussed previously but is very similar to the applet
tag.

For example:
<servlet code=DateServlet.class
codebase=http://blitz/>
<param name=filename value=MyFile.txt>
...
</servlet>

Using Java Web Server B-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Server-Side Includes

Server-Side Include Tags for Servlets (Continued)


● Use the code parameter to define the name of the class file that is
to be loaded.

● The codebase parameter is optional. Use the codebase parameter


to refer to a location where servlet classes are located (defaulting
to server_root/servlets). This parameter may refer to a
remote location for the servlet.

● Use the param name=filename value=MyFile.txt to define


values: name=value request parameters pairs passed in the
request. These must be specified before closing /servlet tag.
✓ The forms module discusses initialization and service parameters in greater detail.

In the example just presented, the contents of the file up to the servlet
tag are sent to the client unmodified. The DateServlet is then loaded
from http://blitz and invoked with the appropriate init and request
parameters (the init parameters are not applicable if the servlet is
already loaded). The output of the DateServlet is embedded into the
response. The contents of the file after the ending servlet tag is then
appended unmodified.
✓ Once the servlet is initialized, the init method is not called again. Normally, if a servlet is
not already loaded on the Web server, it is loaded when invoked by a browser (using one
of the methods in this section). At this time the servlet can accept and parse init
parameters from an .shtml or .html file (such as in the previous server-side include
example). However, at the time of writing this module (August 1998), this functionality did
not work and the only way to receive init parameters was by specifying them using the
Java Web Server parameter editor or through Java Web Server’s use of reflection on a
servlet Bean.

B-18 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Aliases

Overview
Servlet aliases are path name mapping rules that the Java Web Server
uses to invoke servlets. These rules allow you to use a shortcut URL to
call a servlet from your browser, embed a shortcut into your files, or
perform a URL redirect.

Note – The server_root/servlets directory is actually aliased to


the invoker servlet. Therefore, each time you specify
/servlet/servlet_name, you are launching the invoker servlet.

Adding a Servlet Alias


To add a servlet alias using Java Web Server, use the following steps:

1. If Java Web Server is not running, start it now.


✓ The Java Web Server should have been installed prior to these instructions.

2. Log in to the administration applet.

3. Highlight Web Service and click on the Manage button. A separate


Java Web Server Web Service screen will be displayed.

Using Java Web Server B-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Aliases

Adding a Servlet Alias (Continued)


4. Select Aliases from the hierarchical menu. Figure B-6 shows the
Aliases screen.

Figure B-6 Servlet Aliases screen

5. Click on Add to add a new alias.

▼ Alias – The alias is a shortened name used to replace the


/servlet/servletname portion of the servlet’s URL. For
example, hi could be used as an alias for a servlet named
hello. To invoke the hello servlet, type
http://host_name:port/hi

To invoke the servlet instead of the URL, type

http://host_name:port/servlet/hello
▼ Servlet Invoked – The name of the servlet that will be run
when the alias is referenced.

6. Click on Save to save your new alias.

B-20 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Aliases

Arguments
You can add arguments to the name of the servlet that the alias
invokes. To add an argument, enter the name of the servlet followed
by a question mark (?) and the arguments.

Note – You can use this option to perform server redirections; such as,
redirecting users from an old URL to a new URL. For example, you
could alias /oldstuff
to/RedirectServlet?http://www.newcompanyname.com/newstuff
to perform a server redirection. The source code for the
RedirectServlet is located in mod1-basic/examples.

Using Java Web Server B-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Chaining

Overview
For some requests, a chain of ordered servlets can be invoked rather
than just one servlet. The input from the browser is sent to the first
servlet in the chain and the output from the last servlet in the chain is
the response sent back to the browser. Each servlet in the chain has the
inputs and outputs piped to the servlet before and after it, respectively.
A chain of servlets can be triggered for an incoming request through
servlet aliasing or MIME types.

Servlet Chaining and Servlet Aliases


All of the servlets in a servlet chain can be aliased to one URL request.
When a request arrives from that URL, all the servlets in the chain will
be invoked.

Use the servlet alias window to specify a servlet chain alias. To specify
the servlets in the chain: enter the name of each servlet in the Servlet
Invoked field, separated by commas. For example, to chain the
finger, snoop, and date servlets together, type the following in the
Servlet Invoked field:

finger, scoop, date

Servlet Chaining and MIME Types


Servlets should define a MIME type before returning a response. A
servlet can be configured to respond to requests from a particular
MIME type. For example, when a servlet receives a response from the
OutputStream, the response can be piped to the InputStream as a
request to another servlet.

B-22 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Chaining

Servlet Chaining and MIME Types (Continued)


Java Web Server administrators will have to manually edit the
mimeservlets.properties file to create a MIME type servlet chain.
This file resides in:
server_root/properties/server/javawebserver/
webpageservice/

The mimeservlets.properties file maps MIME types to servlet


names (which are also mapped to the servlet’s class files when you
install the servlet).

Servlets in the MIME type chain can be remote servlets. Remote


servlets are brought over before being invoked.

Filtering is one of the primary uses for MIME type servlet chaining.
The first servlet in a servlet chain can act as a filter, parsing incoming
request data, based on the MIME type of the data, and then forward
data to the appropriate servlet for processing.

Using Java Web Server B-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Chaining

Enabling Servlet Chaining


Aside from defining your servlet chain, you must also enable servlet
chaining within Java Web Server. To enable servlet chaining,

1. If Java Web Server is not running, start it now.


✓ The Java Web Server should have been installed prior to these instructions.

2. Log in to the administration applet.

3. Highlight Web Service and click on the Manage button. A separate


Java Web Server Web Service screen will be displayed.

4. Select Site from the hierarchical menu.

5. Select the Options tab to display the Options card (Figure B-7).

Figure B-7 The Options Card

B-24 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Chaining

Enabling Servlet Chaining (Continued)


6. Select the Enabled radio button within the Servlet Chains radio
button group.

7. Click on Save to enable your change.


✓ It is important to remind students that certain servlet features may work differently on
other Web server products. This course focuses on the servlet API; however, certain
features, such as servlet chaining and servlet Beans, are also covered. A future release of
this course may contain information regarding how other Web servers implement these
features. API-related features will be supported on all servers that support the servlet API.

Using Java Web Server B-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Servlet Context

Servlets run within a particular service. Each service maintains its own
environment, which is known as a context. Servlets running within
the same service share the same context. Servlet contexts are
implemented by service developers.

You can use the ServletConfig.getServletContext method to


return a ServletContext for a servlet. Once you have a servlet’s
context, you can invoke methods within the servlet or find out
information about the service under which a servlet is running.

For example:
1 public class First extends GenericServlet {
2 public void service(ServletRequest req,ServletResponse resp) throws
ServletException, IOException {
3 if (condition){
4 Servlet anotherServlet =
servletContext.getServlet("Second");
5 anotherServlet.somemethod()
6 return;
7 }
8 }
9 }

This example demonstrates how to access the methods of servlets


which share the same context (lines 4–5).

B-26 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Using the Documentation

Documentation, in HTML format, for the Java Web Server is installed


in the server_root/system/doc/ directory. The API documentation
is installed in server_root/system/doc/apidoc/packages.html.

To display the documentation, enter the following URL in your Web


browser:

http://host_name:8080/system/doc

You can also display the documentation by clicking on Help in any of


the Server Administrator windows.

Using Java Web Server B-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Additional References

JSERV-INTERST
It is highly recommended that you join the Java Web Server interest
mailing list. This list is used by the Java programming community to
discuss various JavaServer products, including servlet-related issues.

To subscribe to the JSERV-INTERST mailing list:

● Send email to listserv@javasoft.com with the following in the


body of the mail message:
subscribe jserv-interst your_real_name

To unsubscribe from the list:

● Send email to listserv@javasoft.com with the following


message in the body of the mail message:
signoff jserv-interst

B-28 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B
Additional References

Other Servlet References


Table B-1 lists several popular Web sites containing servlet information
Table B-1 Popular Servlet Web Sites.

URL Description

jserv.javasoft.com/ The official Sun


products/java-server/ Microsystems™ Web page for
index.html the JavaServer Product Group
hplbwww.hpl.hp.com/people JSERV-INTERST archives
/ak/archives/jeeves/
www.n-ary.com/ Site specializing in Java servlet
and JDBC technologies
www.developer.com/ The professional developer’s
resource
db.surfspin.com/servlets/ Assorted information and
sample servlets
www.livesoftware.com/ Java servlet solutions for the
enterprise including JRun
javaexchange.com/ Java servlet technologies with
emphasis on database
connectivity

Using Java Web Server B-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
B

B-30 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
CGI Variables and Servlet API C
This appendix lists several common CGI environment variables and
their associated servlet API. Additional servlet APIs, used for
extracting specific information from a request, are listed in a separate
table.

C-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
C
HttpServletRequest Methods

The servlet API provides several methods for parsing individual


values within the HttpServletRequest. Several of these methods
have equivalent environment variables in CGI. These methods, with
their CGI equivalents, are listed in Table C-1.
Table C-1 CGI Variables and Equivalent Servlet API

HttpServletRequest
CGI Variable Description
Method

CONTENT_LENGTH getContentLength Gets size of request


entity
CONTENT_TYPE getContentType Gets the Internet Media
Type of request
SERVER_PROTOCOL getProtocol Gets protocol and
version of request
REMOTE_ADDR getRemoteAddr Gets IP address of agent
sending request
REMOTE_HOST getRemoteHost Gets fully qualified host
name of agent
SERVER_NAME getServerName Gets host name of server
that received request
SERVER_PORT getServerPort Gets port number used
for request
AUTH_TYPE getAuthType Gets authentication
scheme of the request
HTTP_ACCEPT getHeader("Accept")
HTTP_USER_AGENT getHeader
("User-Agent")
HTTP_REFERER getHeader
("Referer")
REQUEST_METHOD getMethod Gets the HTTP method
(GET, POST, PUT)
PATH_INFO getPathInfo Gets any optional extra
path information

C-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
C
HttpServletRequest
CGI Variable Description
Method

PATH_TRANSLATED getPathTranslated Is the same as


getPathInfo, but
translates into real path
QUERY_STRING getQueryString Gets a query string
REMOTE_USER getRemoteUser Gets name of user
making request
SCRIPT_NAME getServletPath Gets the servlet being
invoked
SERVER_SOFTWARE unavailable
GATEWAY_INTERFACE unavailable
REMOTE_IDENT unavailable

CGI Variables and Servlet API C-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
C
Additional Methods

Table C-2 lists additional methods that can be used to extract specific
pieces of information from an HttpServletRequest.
Table C-2 Additional HttpRequestMethods

HttpServletRequest Description
Method

getRealPath Gets real path using


alias rules
getScheme Gets scheme used (such
as HTTP, HTTPS, or
FTP)
getDateHeader Gets value of requested
date header
getIntHeader Gets value of specified
integer header field
getMethod Gets the HTTP method
(such as GET, POST, or
PUT) used in request
getRequestURI Gets part of request’s
URL to left of any query
string

C-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Java Socket Programming D
This appendix gives an overview of low-level TCP/IP structures, a
comparison of TCP/IP protocols, and the Java Socket API.

D-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
IP Addressing

On a TCP/IP network, every machine has a unique address. This is a


32-bit number, which is usually represented using four decimal
numbers separated by dots. For example:
11000000 01100010 01000000 00001100

192.98.64.12

Network Address
To assist with the problems of routing, the addressing space is divided
into ranges, called networks. On a single network, part of the IP
address of each machine is common. That part is called the network
address. The remaining part of the 32-bit range is used to give each
machine a unique address.

Subnet Mask
The subnet mask is also a 32-bit number and is also usually
represented as four decimal values with dot separation. This is used to
distinguish the bits of the IP address range that are common to this
network from those that are used to indicate the host address.

One bit in the subnet mask indicates that the corresponding bit is part
of the network address, while a zero indicates that the corresponding
bit is part of the host address.

On a network, all machines must have the same subnet mask, and
must have the same network address. All host addresses must be
different.

D-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
IP Addressing

Determining the Local Subnet Mask


On a Solaris machine, you can determine the subnet mask, along with
other useful information such as the full IP address of the machine, by
issuing the command
$ ifconfig -a

This command will work on some other UNIX environment variants,


but is not applicable outside of the UNIX environment.

Network Classes
There are three basic categories of network, which are distinguished
by the leading bits of the IP address. These are called class A, B, and C:

● An IP address that starts with 0 (zero) is a class A network.

● An IP address that starts with 1,0 is a class B network.

● An IP address that starts with 1,0 is a class C network.

The significance of these classes is that each defines a number of bits


that must be present in the subnet mask. Class A networks must have
at least the first byte of the subnet mask set to 1s. For class B, the first
two bytes must be set to 1s. For class C, the first three bytes must be
set to 1s.

Two additional classes, called D and E, are also defined:

● Class D network addresses start with 1110 and are multicast


addresses

● Class E network addresses start with four 1 bits and are reserved

Java Socket Programming D-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Name Services

Using 32-bit binary numbers is not very easy for humans, and even
when the convenience form of four decimal numbers is used, it is still
difficult to remember addresses and make mistakes.

To alleviate these problems, naming services are used. A naming


service provides an automatic way for the machine to translate human
textual names into 32-bit numbers that the machine and network
require.

There are three common naming services, hosts files, network


information service (NIS), and domain name services (DNS).

A hosts file may be maintained by a UNIX system in the file


/etc/hosts. If this file is used, it contains address/name pairs, like
this:
127.0.0.1 localhost
192.28.93.102 banana
192.28.93.104 strawberry

NIS is a popular naming service for internal networks, while DNS is


the required naming service for publication of addresses on the
Internet.

The hosts file mechanism predates both NIS and DNS and can be used
to map all addresses in a network. However, this mechanism can be
hard to adminster as each machine in a network must always contain
an updated copy of the hosts file to be able to access every machine.

D-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Name Services

On Solaris machines a file called /etc/nsswitch.conf is used to


control which naming services are used, and in what order they are
searched. The line:
hosts: nis [NOTFOUND=return] dns files

indicates that hostname lookups should be made using NIS only.


Changing the position of the word files so that it preceeds
[NOTFOUND=return] will cause the machine to check the /etc/hosts
file too. Note that root privilege is required if you try to make changes
to either the /etc/hosts or /etc/nsswitch.conf files.

Java Socket Programming D-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Port Numbers

While the IP address identifies a particular machine, an inbound


packet needs to be routed to a particular process. This type of
addressing is done using port addresses.

A port is a 16-bit number, and is commonly used to associate certain


services with a particular well-known port number at the server. A
connection is made between a port number at the client and another
port number at the server. Hence a connection is fully defined by four
32-bit numbers, two port numbers, and two IP addresses.

Port numbers below 1024 are usually reserved for standard services,
such as TELNET, FTP and HTTP. NFS™ uses ports in the 2xxx range
while X Windows uses ports in the 6000 range. Hewlett-Packard
printers use port 9000 for a typewriter mode. Ensure that the port
selected for your service is not in use by other things.

Port assignments are typically listed in the file /etc/services on a


UNIX system although name services such as NIS can be used instead.
You can determine the ports that are currently in use on a UNIX
machine by issuing the command:
$ netstat -a

The default ports used by most protocols are documented in the RFCs
available at http://nic.mil/rfc.

D-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Comparison of Protocols

TCP is generally described as a reliable protocol. This does not mean


that the message will always get through. Rather it means that unless
some sort of hard failure occurs, such as a broken network cable, then
the messages you send will arrive exactly once, in the correct order.
Further, if problems do arise, then both ends will be made aware of the
difficulty.

UDP, by contrast, is an unreliable protocol. When you transmit a


packet, it is forgotten by the sender and no effort is made to ensure
that it arrived or that it was undamaged.

UDP is faster than TCP, mainly in the amount of CPU power it


requires, and has the advantage of being suitable for use with
broadcast and multicast, which TCP is not.

One benefit of UDP is that it is record oriented, while TCP is byte


oriented. This means that if you send a packet of 25 bytes, followed by
another of 15 bytes, TCP considers this a sequence of 40 bytes, with no
special boundary between them. UDP, on the other hand, retains that
boundary, and provided the packets are undamaged, they will arrive
as separate 25- and 15-byte packets.

TCP cannot be used for broadcast or multicast packets, since it


requires a point to point negotiation, and each packet is acknowledged
individually.

Multicast can be considered as a special form of broadcast. It has the


advantage over plain UDP broadcast that it can be rejected by
machines that do not want to receive the data with less CPU power
than is required for the UDP example. Multicast packets are also more
likely to be allowed to pass over routers onto different networks than
is the case for plain broadcast.

Java Socket Programming D-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Java Socket APIs

TCP Sockets
There are two types of TCP sockets: server and client. The server
socket must be associated with a particular port and is constructed like
this:
ServerSocket ss = new ServerSocket(5432);

Once constructed, the accept method waits for incoming


connections. When a connection is received, the accept method
returns a new Socket object.
Socket s = ss.accept();

A client Socket is created with the host name of the server and the
port number on which the server is providing the service.
Socket s = new Socket("banana", 5432);

This constructor blocks until the connection is established, or throws


an exception in case of difficulties.

Once you have a Socket object, the next step is to obtain input and
output streams from that Socket.
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();

These streams are byte oriented and you might need to convert them
to Unicode readers and writers if the communication takes place using
text. This can be done like this:
InputStreamReader ir =
new InputStreamReader(is, "8859_1");
OutputStreamWriter ow =
new OutputStreamWriter(os, "8859_1");

Notice the use of an explicit encoding conversion. This is normally


required when the connection is between unrelated machines. If you
omit this specification, you will find that the bytes are treated as being
in the machine’s local encoding, and this might cause difficulties if the
program is running on a non-American Standard Code for
Information Interchange (ASCII) system.

D-8 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Java Socket APIs

UDP Sockets
UDP sockets are encapsulated in the Java class DatagramSocket. To
construct a socket for use in a server program the socket must be
attached to a particular port. When used in a client program, any free
port can be used and it is usual to allow the system to allocate that
port.

Constructing UDP Sockets

To construct a server UDP socket, use code like this:


DatagramSocket ds = new DatagramSocket(5432);

To construct the client-side socket, use code like this:


DatagramSocket ds = new DatagramSocket();

Receiving UDP Data

Once the socket has been constructed, a packet buffer must be


prepared. This is achieved with the class DatagramPacket. A buffer
for receiving datagrams can be created like this:
byte [] buffer = new byte[1024];
DatagramPacket dp =
new DatagramPacket(buffer, buffer.length);

Packets can then be received from the network by issuing the call
ds.receive(dp);

When the receive method returns, a packet has been collected. The
data can be extracted using the method getData which returns the
buffer. The length of the data is usually less than the length of the
buffer, and the getLength method should be used to determine how
many bytes are valid.

Java Socket Programming D-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Java Socket APIs

UDP Sockets

Sending UDP Data

To send data, build a datagram packet with the host address of the
destination machine and the target port number, like this:
byte [] data = ...// initialize data buffer
DatagramPacket outPacket = new DatagramPacket(data,
data.length,
InetAddress.getByName("banana"),
5432);

Notice the use of the static method getByName in the InetAddress


class. This translates the textual machine name into an address object
suitable for use in this constructor.

Note – The getByName method generally requires that the name


given be in the naming service of the local machine, even if the name
is given as dotted decimal notation.

Once the packet has been constructed, it can be sent from the socket
like this:
ds.send(dp);

Replying to Received Messages

A client determines which machine and port to send packets to from


the server information which is published in some way, the server
needs to send packets back to the machine and port that originated the
incoming packet. To do this, that information must be extracted from
the received packet, like this:
ds.receive(dp); // get incoming request
DatagramPacket replyPacket = new DatagramPacket(
buffer, buffer.length, // should be meaningful!
dp.getAddress(), // reply to sending machine
dp.getPort()); // at senders port
ds.send(replyPacket);

D-10 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
D
Java Socket APIs

Multicast Sockets
The difference between multicasting and normal UDP is that the
listener must “join” the multicast address group. Multicast is
supported in the Java programming language with the
MulticastSocket class, which is a subclass of DatagramSocket. The
significant difference is that the MulticastSocket object has an extra
method, joinGroup.

To receive packets addressed to the multicast group 224.0.0.1 use code


like this:
MulticastSocket ms = new MulticastSocket(5432);
InetAddress addr =
InetAddress.getByName("224.0.0.1");
ms.joinGroup(addr);
byte [] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(
buffer, buffer.length);
ms.receive(dp);

Replying to Broadcast and Multicast Data Transmissions


When a program listens to either broadcast or multicast data, it has a
choice of reply targets. It might be appropriate to send the reply to the
broadcast or multicast address so that all listeners see it. More
typically, however, the reply will be directed to the single machine that
originated the message.

Using the getAddress method of the DatagramPacket object, as


shown earlier in the section ‘‘Replying to Received Messages,” allows
the direction of a reply, even when the original transmission was
broadcast or multicast.

Warning – Multicast is not implemented in the Windows 95 TCP/IP


networking stack.

Java Socket Programming D-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Glossary

Access Control Lists


See ACL.
ACL
Used to control access to resources such as files and directories.
Authentication
A mechanism for determining if a user should be granted access
to a Web page.
Authorization
A mechanism for determining if user should be granted access
to a specific URL.
Basic authentication
Process in which a user enters a user name and a passphrase in
response to a “challenge” by the Web server to pass an access
control check in order to read, write, or execute protected data.
Beans
Reusable software pieces, created by writing Java classes that
adhere to the JavaBeans component model.
Broadcast
A message sent to a special IP address monitored by one or
more clients.
Client pull
A mechanism whereby a client makes requests to a server to
have its information updated.
Client push
A mechanism whereby a server automatically sends
information, as it is updated on the server, to a client.

Glossary-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Cookies
A mechanism for storing a variable and its associated value on
the Web browser.
Connection Pool
A pool of persistent (reusable) connections that can be used by a
database client, such as a servlet, as needed.
Declarations
A JavaServer Pages tag that identifies class-wide variables and
methods used by the generated servlet.
Digest authentication
A form of authentication whereby no password is sent over the
wire.
Directives
A JavaServer Pages tag that allows you to modify certain
characteristics of the JavaServer page and resulting servlet.
Dynamic HTML
The HTML generated by a common gateway interface (CGI)
script or servlet.
Expressions
A JavaServer Pages tag that contains script language
expressions which are replaced with the values for those
expressions, once an expression has been resolved.
Hypertext Transfer Protocol
See HTTP.
HTTP
The request/response protocol used by most Web servers to
communicate with Web browsers on the Internet.
HttpServlet
A subclass of the GenericServlet abstract class which is used to
develop HTTP-based servlets.
JavaBeans
A portable, platform-independent component model written in
the Java programming language.
JavaServer Pages
See JSP.

Glossary-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
JSP
Web pages that contain a combination of HTML and code
written in a scripting language such as the Java programming
language.
Multicast
A message sent to a special IP address monitored by a specific
group of clients.
Multithreaded-hot
Refers to code that is both multithreaded-safe and optimized for
performance.
Multithreaded-safe
Refers to code whereby multiple threads can access and change
volatile data such as class variables, without corrupting that
data.
Mulitier
A model for distributed computing consisting of multiple
clients talking to one or more servers which, in turn, talk to one
or more additional servers.
Query String
A portion of a URL containing request parameters.
Scriptlet
The portion of scripting code used to add functionality to the
HTML within a JavaServer page.
Security realm
A server-side entity containing users, groups, and their
associated access control lists.
Services
Bodies of code that implement an application-level protocol
such as file transfer protocol (FTP), dynamic host configuration
protocol (DHCP), or hypertext transfer protocol (HTTP).
Service method
The method within a servlet invoked for each request to the
servlet.
Servlet
Modules of code that run inside request/response-oriented
services, extending these service in some manner.

Glossary Glossary-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Servlet aliases
Pathname mapping rules that the Java Web Server uses to
invoke servlets.
Servlet Bean
A servlet that adheres to the JavaBeans design patterns,
particularly to the design pattern for introspection.
Servlet context
A service’s environment shared among the servlets within that
service.
Servlet engine
Required by Web servers to run servlets.
Servlet sandbox
An isolated group of threads used to run untrusted Java
servlets.
Session
The data associated with a collection of related HTTP
transactions made by one browser to one server.
SSL server authentication
A mechanism whereby a server is authenticated to a Web
browser to ensure a secure transaction.
Statelessness
Refers to the lack of a mechanism for keeping track of a request
or request data sent using a Web browser.
TCP
A connection-oriented transmission protocol; for reliability, TCP
requires a connection before a message can be sent.
Time-extended connection
A mechanism allowing new data to be sent to the client,
automatically, at regular intervals.
Transmission Control Protocol
See TCP.
Trusted servlet
Servlets that are assumed to be secure and are granted full
access to system resources.
Two-tier
A model for distributed computing consisting of multiple
clients talking to one or more servers.

Glossary-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
UDP
A connectionless transmission protocol; UDP does not require
setting up a connection before sending a message.
Untrusted servlet
Servlets that cannot be assumed to be secure, such as a remote
servlet, which are not granted full access to system resources.
URL rewriting
Allows a session to be tied to a browser by adding a session
Identifier (ID) to a requested URL.
User Datagram Protocol
See UDP.

Glossary Glossary-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Index

A C
Acessor methods 9-11 Cache-Control 9-9
ACL 8-12 CGI
ACTION 2-32 an example form processing
addConnection 4-26 script 2-11, 2-13
addCookie 6-9 example uses for 1-4 to 1-5
Authentication 8-6 invocation of 1-11
basic 8-9 invoking a form processing
challenge-response 8-7 script 2-19
digest 8-10 overview of 1-4
HTTP types 8-8 to 8-11 parsing the form
passphrase 8-7 request 2-16 to 2-17
public key protocol 8-7 print statements 10-5
SSL server 8-10 to 8-11 println statements 10-5
Authorization 8-6 processing form data with 2-4
an overview of 8-7 reading the form request 2-15
request and response
B mechanism of 1-6 to 1-7
returning a response 1-10
Bean 9-11, 9-12, 9-15, 9-19, 10-25, returning a response after
10-27, 10-28 processing a form 2-18
an overview of 9-4 setting content type 1-9
customization 9-5 variables and equivalent
events 9-5 servlet APIs 2-29
functionality of 9-5 Web server support for 1-12
introspection 9-5 with HTTP 1-7
persistance 9-5 class loaders
Beans 9-4 when is a class loaded? 6-3
an overview of 9-4 Class.forName 4-12
functionality of 9-5 CLASSPATH 3-6, 9-17, 9-18
BufferedReader 2-28 Client Pull
dynamic HTML updates 7-7
Client pull 7-5 to 7-6

Index-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
dynamic Java updates 7-8 E
closeAll 4-32 encodeRedirectURL 6-25
ConnectionPool 4-25 encodeURL 6-25
Continuous or Transient TCP
Connections 7-8 to 7-10
Cookie 6-9 G
Cookies 6-6, 6-7 to 6-10, 6-26 GenericServlet 1-20
an example of adding 6-9 GET 2-9, 2-23, 2-27, 2-32, 6-19
an example of creating 6-9 get 9-12
an example of retrieving 6-10 getConnection 4-13, 4-28
compared with sessions 6-26 getContentLength 2-29
programming with 6-8 getCookies 6-10
using to tie a session to a getInitParameter 3-10
browser 6-24 getInitParameterNames 3-10
CORBA/IDL 4-4, 4-7, 5-1, getInputStream 2-28
5-26 to 5-27 getLastModified 2-23
a comparison with RMI 5-27 getNewConnection 4-27
createStatement 4-14 getOuputStream 1-24
getParameter 2-27
D getParameterNames 2-26, 2-27
getParameterValue 2-30
Datagram 7-11
getParameterValues 2-26, 2-27
DELETE 2-9, 2-23
getQueryString 2-27
destroy 3-2, 3-4, 3-19, 3-20, 3-21,
getReader 2-28
3-22, 3-25
getServletConfig 3-10
Destroy method 3-18
getServletInfo 2-31, 9-12
concurrency issues 3-20
getValue 6-12, 6-21
four tasks 3-22
getWriter 1-24
handling service threads at
servlet termination 3-21
Distributed H
applications 4-4 to 4-6 HEAD 2-9, 2-23
distributed computing HTML 1-4, 4-17, 6-14, 6-19, 7-7,
Java technologies 4-7 10-6, 10-17, 10-20, 10-21, 10-22
doDelete 2-23 an example form 2-5
doGet 1-21, 2-23 forms 2-4
doOptions 2-23 forms and servlets 2-20
doPost 2-23, 6-14, 6-16 the tag 2-7
doPut 2-23 the ACTION attribute 2-11
doTrace 2-23 the ENCTYPE
DriverManager 4-13 attribute 2-11
Dynamic content the METHOD attribute 2-8
generating 10-4 the tag 2-12
Dynamic html 1-10 HTTP 6-11, 6-14, 7-4, 7-7, 8-5,
8-6, 8-8, 8-9, 8-10, 8-13
benefits and limitations of

Index-2 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
statelessness 6-4 getConnection 4-28 to
benefits of state 6-5 to 6-6 4-29
method types 2-8 to 2-10 getNewConnection 4-
method types and service 27
methods 2-22 to 2-24 releaseConnection 4-3
HttpRequest 1-21 0 to 4-31
HttpResponse 1-21 implementation 4-20
HTTPS 8-11 items to consider 4-19
HttpServlet 1-20, 2-22, 2-24, 3-2, the connection pool
10-14 client 4-21
HttpServletRequest 2-24, 10-18 two components of 4-20
HttpServletResponse 1-22, 6-25, creating and executing a
10-18 query 4-14
HttpSession 6-12 establishing a connection to
HttpUtils 6-17 the database 4-13
loading the database
I driver 4-12
parsing and displaying the
in 10-18 results 4-15
init 3-2, 3-4, 3-7, 3-8, 3-9, 3-11, JSP 10-1, 10-8 to 10-38
3-18, 3-19, 6-14 a definition of 10-8
Init method additional
configuring initialization guidelines 10-20 to 10-21
paramters 3-11 an example page 10-10
retrieving initialization declarations 10-15
parameters 3-10 directives 10-12
INPUT 2-12 the extends variable 10-14
the implements
J variable 10-13
JAR 8-38, 9-14, 9-16, 9-17 the import variable 10-13
Java technologies 4-7 the language
JavaBeans 9-2, 9-12 variable 10-12
an overview of 9-4 the method variable 10-13
JDBC 4-1, 4-4, 4-7, 4-8, 5-1 expressions 10-19
an example DBServlet an example
servlet 4-9 to 4-16 expression 10-19
and concurrency 4-17 scriptlet 10-17 to 10-18
and servlets 4-17 the in variable 10-18
closing the connection 4-16 the out variable 10-18
connection pools 4-18 to 4-32 the request variable 10-18
an example connection the response variable 10-18
pool client 4-23 the tag 10-22 to 10-28
example API 4-24 a ColorGameBean
addConnection 4-26 example 10-23 to 10-24
closeAll 4-32 declaring a Bean 10-25,
constructor 4-25 10-27

Index Index-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
the beanName println 1-24, 10-4, 10-7
attribute 10-28 PrintWriter 1-24, 2-29
the create attribute 10-27 PUT 2-9, 2-23
the introspect putValue 6-12
attribute 10-26
the name attribute 10-25 Q
the scope
attribute 10-27 to 10-28 Query string 2-27
request 10-28
session 10-28 R
the type attribute 10-26 readLine 2-28, 2-29
the varname Realms 8-12, 8-12 to 8-15
attribute 10-26 CertificateRealm 8-14
the SCRIPT tag 10-15 to 10-16 defaultRealm 8-14
two benefits of 10-8 to 10-9 NTRealm 8-13
UNIXRealm 8-13
M with Java Web
Malicious code 8-4 Server 8-13 to 8-15
METHOD 2-11 releaseConnection 4-30
Multithreaded-hot Remote 5-8
recommendations for Remote servlets 3-6
code 3-16 RemoteUser property 8-39 to ??
Multithreaded-safe 3-14 request 10-18
code samples for response 10-18
synchronized access ResultSet 4-15
methods 3-15 ResultSetMetaData 4-15
recommendations for RMI 4-4, 4-7, 5-1, 5-4 to 5-25
code 3-15 a comparison with
Multi-tier model 4-5 to 4-6 CORBA/IDL 5-27
an example RMI servlet
solution 5-12 to 5-25
O an overview of 5-4 to 5-5
ObjectOutput 9-15 and servlets 5-11
ObjectOutputStream 9-15 implementing a client 5-9
OPTIONS 2-9 implementing a server 5-8
out 10-18 installing and invoking the
OutputStream 1-24 server, client, and
registry 5-10
P interaction between client,
server, and
PageCompileServlet 10-8, 10-9, registry 5-6 to 5-7
10-20, 10-29 to 10-34 rmiregistry 3-11
parsePostData 6-17
parseQueryString 2-27
POST 2-9, 2-23, 2-32, 6-14, 6-17 S
print 10-7 Sanity checking 8-41

Index-4 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
SCRIPT 10-15 api equivalents for CGI
Scriptlet 10-17, 10-20 variables 2-29
Security configuring initialization
authentication parameters 3-11
types of 8-8 to 8-11 definition of 1-13
authorization and displaying information about
authentication 8-6 to 8-7 a servlet 2-31
back doors 8-5 example uses for 1-14
bacteria 8-5 invoking an example form
eavesdropping 8-5 processing servlet 2-32
logic bombs 8-5 invoking an example
realms 8-12, ?? to 8-15 servlet 1-25 to 1-27
RemoteUser parsing a form request 2-26
property 8-39 to 8-40 parsing all
sanity checking 8-41 requests 2-26 to 2-27
servlet 8-34 to 8-38 parsing an HTTP GET query
servlet sandbox 8-34 to 8-36 string 2-27
signed network servlets 8-38 parsing HTTP POSTs with
tools and toolkits 8-4 binary or text
trojan horses 8-5 data 2-28 to 2-29
trusted servlets 8-37 println statements 10-6
unsigned network println statments,
servlets 8-38 shortcoming of 10-7
untrusted servlets 8-34 request and response
viruses 8-5 mechanism of 1-15 to 1-16
Web server retrieving initialization
major threats 8-4 to 8-5 parameters 3-10
worms 8-5 returning a response 1-24
SecurityManager 8-36 returning a response from a
Serializable 9-13 form processing
Server push 7-5 to 7-6 servlet 2-30
dynamic HTML updates 7-7 sandbox 8-34 to 8-36
dynamic Java updates 7-8 saving ServletConfig 3-10
service 2-24, 3-4, 3-12, 9-11 security 8-34 to ??
Service method 1-21 setting content
concurrency issues 3-13 type 1-22 to 1-23, 2-25
ServletRequest 3-12 signed network 8-38
ServletResponse 3-13 the destroy method 3-18
Servlet the init method 3-7
a HelloWorld the service method 1-21, 3-12
example 1-18 to 1-19 trusted 8-37
an example form processing unsigned network 8-38
servlet 2-21 untrusted 8-34
an init method with HTTP 1-17
example 3-8 to 3-10 with JDBC 4-17
and RMI 5-11 writing exceptions to log

Index Index-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
files 1-25 Sessions 6-6, 6-11 to ??
Servlet aliases 1-27 an example Login and Secret
Servlet bean 9-6 servlet 6-13 to 6-21
a definition of 9-6 compared with cookies 6-26
a SampleBean the HTTPSession
example 9-7 to 9-8 Interface 6-12
an invocation set 9-12
example 9-20 to ?? setContentType 1-22, 2-25
automatic reloading of 9-18 setHeader 1-23, 9-9
deserializing beans 9-17 setIntHeader 1-23
generating a serialized Signed network servlets 8-38
bean 9-16 SingleThreadModel 3-17
get and set acessor SQLException 3-20
methods 9-11 to 9-12 SSL 8-10
introspected
properties 9-11 to 9-12 T
introspection 9-6
invocation of 9-19 TCP 7-9
invocation using an URL 9-22 Theft or alteration of data 8-4
locations for 9-17 Time-extended
packaging of 9-16 connection 7-4 to 7-14
writing to a serialization an overview of 7-4
file 9-13 to 9-14 broadcast and multicast
Servlet context 1-25 UDP 7-13 to 7-14
Servlet engine 1-28 continuous or transient TCP
Servlet lifecycle connections 7-9
loading and instantiating a implementation
servlet 3-5 options 7-5 to 7-6
remote servlets 3-6 using UDP 7-11 to 7-12
servlets in TRACE 2-9, 2-23
server_root/servlets/ 3-6 Trusted servlets 8-37
servlets on the Two-tier model 4-4 to 4-5
CLASSPATH 3-6
system class loader 3-5 U
the destroy method 3-18 UDP 7-11, 7-13
the four steps of 3-4 UDP broadcast 7-13
the init method 3-7 UDP multicast 7-14
the service method 3-12 UnavailableException 3-9
ServletConfig 3-9, 3-10, 9-11 UnicastRemoteObject 5-8
ServletContext 3-20 Unsigned network servlets 8-38
servletContext 1-25 Untrusted servlets 8-34
servletInfo 9-12 URL rewriting 6-24 to 6-25
ServletInputStream 2-28, 2-29
ServletOutputStream 1-24
ServletRequest 3-12 W
ServletResponse 3-12 writeObject 9-15

Index-6 Beyond CGI: Developing Java Servlets


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Copyright 1998 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits
réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune
forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.
Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un
copyright et licencié par des fournisseurs de Sun.
Des parties de ce produit pourront être dérivées du systèmes Berkeley 4.3 BSD licenciés par l’Université de Californie.
UNIX est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company Ltd.
Sun, Sun Microsystems, le logo Sun, Java, JavaBeans, Java Web Server, JavaServer, JavaServer Pages, JDBC, JavaScript,
JDK, et Solaris sont des marques déposées ou enregistrées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.
Toutes les marques SPARC, utilisées sous licence, sont des marques déposées ou enregistrées de SPARC International, Inc.
aux Etats-Unis et dans d’autres pays. Les produits portant les marques SPARC sont basés sur une architecture développée
par Sun Microsystems, Inc.
Toutes les marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARC
International, Inc. aux Etats-Unis et dans d’autres pays.
Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
Netscape Navigator est une marque de Netscape Communications Corporation.
L’interfaces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour larecherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent
en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
L’accord du gouvernement américain est requis avant l’exportation du produit.
Le système X Window est un produit de X Consortium, Inc.
LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET
GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA
LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE
MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

Please
Recycle

You might also like