You are on page 1of 278

Sun Educational Services

Beyond CGI: Developing Java


Servlets

SL-310

Sun Educational Services

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Preface

About This Course

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Course Goal
Primary goal of this course:
• Establish an understanding of servlet development, in
contrast to common gateway interface (CGI), and create
several servlet solutions

Beyond CGI: Developing Java Servlets Preface, slide 2 of 16


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

Course Overview
• Servlets:
• Are Java™ programming objects
• Extend the functionality of server-based services
• Are a robust replacement for CGI scripts
• The course:
• Focuses on developing servlets to solve real-world
problems
• Discusses servlet development issues
• Introduces major servlet-related features of Web
servers
Beyond CGI: Developing Java Servlets Preface, slide 3 of 16
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
Course Map
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

Beyond CGI: Developing Java Servlets Preface, slide 4 of 16


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

Module-by-Module Overview
• Module 1 – Servlet Basics
• Module 2 – Forms Processing With Servlets
• Module 3 – Servlet Life Cycle
• Module 4 – Database Access
• Module 5 – RMI and CORBA/IDL
• Module 6 – Persistent State in HTTP Servlets

Beyond CGI: Developing Java Servlets Preface, slide 5 of 16


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

Module-by-Module Overview
• Module 7 – Time Extended Connections
• Module 8 – Servlet Security
• Module 9 – Servlet Beans
• Module 10 – Dynamic Web Content

Beyond CGI: Developing Java Servlets Preface, slide 6 of 16


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

Course Objectives
• 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 remote method invocation (RMI) and common
object request broker architecture/interface definition
language (CORBA/IDL) servlet solutions.

Beyond CGI: Developing Java Servlets Preface, slide 7 of 16


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

Course Objectives
• Create part of a Web shopping servlet that uses session
tracking to keep track 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.

Beyond CGI: Developing Java Servlets Preface, slide 8 of 16


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
Skills Gained by Module
Meaning of:
• Black boxes
• Gray boxes
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.
Examine the JavaServer Pages technology.

Beyond CGI: Developing Java Servlets Preface, slide 9 of 16


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

Guidelines for Module Pacing

Module Day 1 Day 2 Day 3

About This Course AM


Servlet Basics AM
Forms Processing With Servlets AM/PM
Servlet Lifecycle 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

Beyond CGI: Developing Java Servlets Preface, slide 10 of 16


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

Topics Not Covered


• Object-oriented concepts
• Object-oriented design and analysis
• Java programming language constructs
• System administration concepts

Beyond CGI: Developing Java Servlets Preface, slide 11 of 16


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

How Prepared Are You?


• Are you experienced using Web browsers?
• Do you have Java programming experience?
• Are you comfortable learning new application
programming interfaces (APIs) ?
• Are you successful in courses that use a hands-on
approach?

Beyond CGI: Developing Java Servlets Preface, slide 12 of 16


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

Introductions
• Name
• Company affiliation
• Title, function, and job responsibility
• Distributed computing experience
• CGI programming experience
• Server-side program development experience
• Reasons for enrolling in this course
• Expectations for this course

Beyond CGI: Developing Java Servlets Preface, slide 13 of 16


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

How to Use Course Materials


• Course map
• Relevance
• Overhead image
• Lecture
• Exercise
• Check your progress
• Think beyond

Beyond CGI: Developing Java Servlets Preface, slide 14 of 16


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

Icons
• Demonstration

• Reference

• Discussion

• Exercise

Beyond CGI: Developing Java Servlets Preface, slide 15 of 16


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

Typographical Conventions
• Courier – Commands, files, and directories, on-screen
computer output

• Courier bold – Input you type

• Courier italic – Variables and command-line


placeholders

• Palatino italics – Book titles, new words or terms, words


that are emphasized

Beyond CGI: Developing Java Servlets Preface, slide 16 of 16


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

Module 1

Servlet Basics

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 1, slide 2 of 26


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

Common Gateway Interface (CGI)


• Allows Web client to execute programs on the server
• Example uses:
• Providing an entry point to a Web server utility
• Returning database information
• Performing a computation

Beyond CGI: Developing Java Servlets Module 1, slide 3 of 26


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

CGI Request and Response

Gateway
programs 2

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

Browser
(WWW client)
HTTP (Web)
server

Beyond CGI: Developing Java Servlets Module 1, slide 4 of 26


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

CGI and HTTP


• HTTP is the request/response protocol used by most
Web servers.
• HTTP response headers indicate type of data in the
response.

Beyond CGI: Developing Java Servlets Module 1, slide 5 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example HelloWorld
CGI Script
• helloworld.pl CGI script
1 #!/usr/dist/pkgs/perl/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 }

Beyond CGI: Developing Java Servlets Module 1, slide 6 of 26


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

Setting Content Type


• Header type for response set to:
Content-Type:text/html
• Content type is used to specify the Multipurpose
Internet Mail Extension (MIME) data type.
• Specify the MIME type and sub-type when using the
content type header.

Beyond CGI: Developing Java Servlets Module 1, slide 7 of 26


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

Returning a Response
• Perl print command used to compose the body of the
response.
• Hypertext markup language (HTML) generated by a
script is called dynamic HTML.

Beyond CGI: Developing Java Servlets Module 1, slide 8 of 26


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

Invoking the Example CGI Script


• Scripts are placed in server_root/cgi-bin/
directory.
• Scripts are invoked with a Web browser.
• helloworld.pl script is invoked using:
http://host_name:port/cgi-bin/
helloworld.pl

Beyond CGI: Developing Java Servlets Module 1, slide 9 of 26


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

Web Server and CGI Support


• Most Web servers support CGI scripts.
• Most Web servers support several CGI scripting
languages:
• Perl
• C
• Tool command language (TCL)

Beyond CGI: Developing Java Servlets Module 1, slide 10 of 26


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

What Is a Servlet?
• A module that runs inside and enhances request/
response-oriented services.
• Example uses:
• Allowing access to remote objects
• Tracking large amounts of information
• Allowing collaboration among multiple users

Beyond CGI: Developing Java Servlets Module 1, slide 11 of 26


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

Servlet Request and Response

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

Beyond CGI: Developing Java Servlets Module 1, slide 12 of 26


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

HTTP and Servlets


• Servlets were developed for the HTTP protocol as an
alternative to CGI-based solutions.
• HttpServlet class is used to develop HTTP-based
servlets.

Beyond CGI: Developing Java Servlets Module 1, slide 13 of 26


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

An Example HelloWorld Servlet


• HelloWorld servlet:
• Invoked by Web browser
• Returns a string
• HTTP protocol generates HTTP GET method

• Servlet is a compiled .java file (.class file) stored on


Web server.

Beyond CGI: Developing Java Servlets Module 1, slide 14 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example HelloWorld
Servlet
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 }

Beyond CGI: Developing Java Servlets Module 1, slide 15 of 26


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

HttpServlet
• Example class extends HttpServlet, an implementation
of javax.servlet.GenericServlet.
• HttpServlet is used to develop HTTP-based servlets.
• Servlets can be created to support services other than
HTTP.

Beyond CGI: Developing Java Servlets Module 1, slide 16 of 26


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

The service Method


• doGet method called for each request to the servlet.
• doGet is one of several HTTP methods supported.
• doGet is used because HTTP protocol generates a GET.
• doGet accepts HttpRequest and HttpResponse
objects.

Beyond CGI: Developing Java Servlets Module 1, slide 17 of 26


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

Setting Content Type


• HttpServletResponse object is used to generate a
response.
• Content type set through
response.setContentType method.
• Length of response set with the setContentLength
method.
• Fields added to response header using setHeader
and setIntHeader methods.

Beyond CGI: Developing Java Servlets Module 1, slide 18 of 26


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

Returning a Response
• PrintWriter and ServletOutputStream – Used for
returning the body of a response to a client
• response.getWriter – Used for text data
• response.getOutputStream – Used for binary data
• Options for printing the response
• Example uses PrintWriter.println
• PrintWriter is closed using out.close

Beyond CGI: Developing Java Servlets Module 1, slide 19 of 26


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

Writing Exceptions to Log Files


• Context – Environment maintained by each service
• Servlet contexts
• Same for servlets running in the same service
• Implemented by service developers for a Web server
• getServletContext used in the example
• javax.servlet.servletContext interface
• Two log methods for debugging servlets

Beyond CGI: Developing Java Servlets Module 1, slide 20 of 26


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

Invoking the Example Servlet


• Servlets placed in server_root/servlets/ directory
• Servlet can be invoked directly:
http://fuggles:8080/servlet/HelloWorld
• Use servlet/ in uniform resource locator (URL)
instead of servlets/
• Java Web Server™ servlet aliasing

Beyond CGI: Developing Java Servlets Module 1, slide 21 of 26


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

Web Server Servlet Support


• Servlets require servlet “engine” to run
• Servlet support provided by several Web servers,
including Java Web Server.

Beyond CGI: Developing Java Servlets Module 1, slide 22 of 26


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

Review of Servlet Basics


• Extending HttpServlet
• Overriding a service method to accept servlet requests
• Setting the content type
• Using getPrintWriter or getServletOutputStream
• Using the println method to generate dynamic HTML
• Using output.close
• Logging information using getServletContext.log

Beyond CGI: Developing Java Servlets Module 1, slide 23 of 26


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

Exercise: Developing a Simple HTTP


Servlet
• Exercise objective: Create a servlet that responds to the
GET method, and one that writes to the event log.

• Preparation: See documentation in Appendix B and at


http://host_name:8080/system/doc/index.html
• Tasks
• Create BasicServlet.java
• Configure and invoke BasicServlet.java
• Create an event_log servlet
• Exercise summary

Beyond CGI: Developing Java Servlets Module 1, slide 24 of 26


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

Check Your Progress


• 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

Beyond CGI: Developing Java Servlets Module 1, slide 25 of 26


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

Think Beyond
This module primarily discussed handling servlet responses.
What might you do as part of handling a request to a servlet?

Beyond CGI: Developing Java Servlets Module 1, slide 26 of 26


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

Module 2

Forms Processing With Servlets

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 2, slide 2 of 30


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

A Basic Form Solution


• Two items are required:
• HTML form
• CGI script or servlet for processing form data

Beyond CGI: Developing Java Servlets Module 2, slide 3 of 30


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

• HTML forms contain fields, buttons,


and checkboxes, and a submit button.

Beyond CGI: Developing Java Servlets Module 2, slide 4 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example HTML Form
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>

Beyond CGI: Developing Java Servlets Module 2, slide 5 of 30


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

The <FORM> Tag


• <FORM> tag parameters:
• METHOD
• ACTION
• ENCTYPE

Beyond CGI: Developing Java Servlets Module 2, slide 6 of 30


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

METHOD
• Identifies how data will be sent from browser to Web
server:
• GET
• HEAD
• POST
• PUT
• DELETE
• TRACE
• OPTIONS

Beyond CGI: Developing Java Servlets Module 2, slide 7 of 30


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

ACTION and ENCTYPE


• ACTION – Specifies the destination for the form
information (such as CGI script or servlet)
• ENCTYPE – Encodes the data; can be used only with POST
method

Beyond CGI: Developing Java Servlets Module 2, slide 8 of 30


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

The <INPUT> Tag


• Identifies the individual input fields in a form
• Identifies the button used to submit the data

Beyond CGI: Developing Java Servlets Module 2, slide 9 of 30


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

An Example Form-Processing Script


• Form.pl CGI script:
• Setting content type
• Reading the request
• Parsing the request
• Returning a response

Beyond CGI: Developing Java Servlets Module 2, slide 10 of 30


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

An Example Form-Processing Script


• Setting content type
• Reading the request
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

Beyond CGI: Developing Java Servlets Module 2, slide 11 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Form-
Processing Script
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 }

Beyond CGI: Developing Java Servlets Module 2, slide 12 of 30


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

Parsing the Request


• $buffer contains the message body parsed into pairs:
@pairs = split(/&/, $buffer);

• The stream before being parsed:


LNAME=Richards&NAME=ani.richards@sun.com&CHECKBOX=on&
SELECT=OPTION+1

• A message with multiple values:


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

Beyond CGI: Developing Java Servlets Module 2, slide 13 of 30


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

Returning a Response
foreach $pair (@pairs) {

($name, $value) = split(/=/, $pair);

...

print "$name: $value<BR>";

Beyond CGI: Developing Java Servlets Module 2, slide 14 of 30


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

Invoking the Example Form-


Processing Script
• HTML files are in server_root/public_html/.
• CGI scripts are in server_root/cgi-bin/.
• Invoke HTML form page from your browser:
http://host_name:port/form.html
• CGI script is invoked by the <ACTION> attribute of the
<FORM> tag when submit button is clicked.

Beyond CGI: Developing Java Servlets Module 2, slide 15 of 30


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

Forms and Servlets


• Use previous HTML form, but change value for the
ACTION attribute:
• Using CGI:
<FORM METHOD="POST" ACTION="/cgi-bin/form_info.pl">

• Using servlets:
<FORM METHOD="POST" ACTION="http://fuggles:8080/
servlet/SimpleFormServlet">

Beyond CGI: Developing Java Servlets Module 2, slide 16 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Form-
Processing Servlet
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 SimpleFormServ-
let.\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 }

Beyond CGI: Developing Java Servlets Module 2, slide 17 of 30


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

HTTPServlet Service Methods


• Override the HTTPServlet service method that
corresponds to the type of HTTP method in a request:
• doGet
• doPost
• doPut
• doTrace
• doOptions
• service (not typically overridden)
• HTTPServletRequest and HTTPServletResponse
objects

Beyond CGI: Developing Java Servlets Module 2, slide 18 of 30


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

Setting Content Type


• Servlet sets content type using
response.SetContentType method.

Beyond CGI: Developing Java Servlets Module 2, slide 19 of 30


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

Parsing the Request


• For all requests
• getParameterNames
• getParameterValues
• For HTTP GET query string
• Sending parameters:
http://fuggles:8080/servlet/
Survey?name=skiing&level=1&years=15

• getQueryString
• parseQueryString

Beyond CGI: Developing Java Servlets Module 2, slide 20 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
HTTP POSTs With Binary or
Text (Localized) Data
• request.getReader with
BufferedReader
• request.getInputStream with
ServletInputStream
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();

For CGI variables and equivalent servlet


APIs, see Appendix C.
Beyond CGI: Developing Java Servlets Module 2, slide 21 of 30
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Returning a Response
• Names of request parameters are saved in Enumeration
object.
• getParameterValue method is used to extract value
for each name.
• println method is used to return a response.

Beyond CGI: Developing Java Servlets Module 2, slide 22 of 30


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

Displaying Information About a


Servlet
• getServletInfo method – provides information about
the servlet to the Web server:
• Servlet description
• Author
• Version number

Beyond CGI: Developing Java Servlets Module 2, slide 23 of 30


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

Invoking the Example Form-


Processing Servlet
• HTML files placed in server_root/public_html/
• Servlets placed in server_root/servlets/
• Invoke HTML form page from your browser:
http://host_name:port/form.html
• Servlet is invoked by the <ACTION> attribute of the
<FORM> tag when submit button is clicked

Beyond CGI: Developing Java Servlets Module 2, slide 24 of 30


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

Review of Form Servlets


• Modifying a form’s ACTION tag
• Extending HTTPServlet
• Overriding an HTTPServlet service method (doGet or
doPost, usually)
• Setting the content type using setContentType

Beyond CGI: Developing Java Servlets Module 2, slide 25 of 30


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

Review of Form Servlets


• Parsing the request
• getParameterNames and getParameterValues
• getQueryString
• getReader
• getInputStream
• Submitting a response: res.getPrintWriter or
res.getServletOutputStream
• Using the println method of PrintWriter or
ServletOutputStream
• (Optional) Overriding getServletInfo
Beyond CGI: Developing Java Servlets Module 2, slide 26 of 30
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Exercise: Developing Form-


Processing Servlets
• Exercise objective: Create a feedback form and a form-
processing servlet
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Create BasicForm.java
• Configure and invoke BasicForm.java
• Create a feedback form and form-processing servlet
• Exercise summary
Beyond CGI: Developing Java Servlets Module 2, slide 27 of 30
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Check Your Progress


• 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 and servlet from an
HTML form
• List the seven HTTPServlet service methods

Beyond CGI: Developing Java Servlets Module 2, slide 28 of 30


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

Check Your Progress


• Explain the differences between getParameterNames,
getParameterValues, getParameter,
getQueryString, parseQueryString,
getPrintWriter, and getServletOutputStream
servlet APIs
• Identify the use of the getServletInfo method
• Write a form-processing servlet

Beyond CGI: Developing Java Servlets Module 2, slide 29 of 30


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

Think Beyond
A servlet can receive all types of parameters from form data to
file and path information, 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?

Beyond CGI: Developing Java Servlets Module 2, slide 30 of 30


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

Module 3

Servlet Life Cycle

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 3, slide 2 of 27


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

Servlet Life Cycle


• Four steps:
• Loading and instantiation of the servlet (creation of a
servlet instance) by a service
• Invocation of init
• Invocation of service
• Invocation of destroy

Beyond CGI: Developing Java Servlets Module 3, slide 3 of 27


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

Loading and Instantiating a Servlet


• Class loaders – load and instantiate servlet classes
• Servlets on the CLASSPATH – loaded by system class
loader
• Servlets in server_root/servlets/ – use special
Java Web Server class loader
• Remote servlets – must define a codebase

Beyond CGI: Developing Java Servlets Module 3, slide 4 of 27


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

The init Method


• Invoked by a service when servlet is loaded
• Called only once
• Cannot be reloaded unless it has been removed by its
destroy method
• As soon as it returns, servlet can receive client requests
• Called only once, so no concurrency issues during
servlet initialization

Beyond CGI: Developing Java Servlets Module 3, slide 5 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example init Method
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 }

Beyond CGI: Developing Java Servlets Module 3, slide 6 of 27


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

An Example init Method


• Accepting a ServletConfig object with initialization
parameters and configuration methods

• Saving ServletConfig – for later use


• Retrieving initialization parameters
• getInitParameter
• getInitParameterNames

Beyond CGI: Developing Java Servlets Module 3, slide 7 of 27


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

Configuring Initialization Parameters


• Servlet initialization parameters are configured within a
Web server.
• Process differs among Web servers.
• Java Web Server provides a property editor.

Beyond CGI: Developing Java Servlets Module 3, slide 8 of 27


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

The service Method


• Processes client requests in separate servlet thread
• Receives two objects: ServletRequest and
ServletResponse

• ServletRequest – Gives a servlet access to


information

• ServletResponse – Provides an output stream and


writer to send reply data
• Handling concurrency issues

Beyond CGI: Developing Java Servlets Module 3, slide 9 of 27


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

Multithreaded-Safe Servlets
• Multiple threads safely access same data
• Recommendations for code are:
• Define appropriate access types for methods and
variables
• Synchronize all instance methods accessing critical
data
• Create access methods for accessing class variables

Beyond CGI: Developing Java Servlets Module 3, slide 10 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Synchronized
Access Method
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 }

Beyond CGI: Developing Java Servlets Module 3, slide 11 of 27


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

Multithreaded-Hot Servlets
• Multithreaded-safe code that is optimized for
performance.
• Recommendations for code:
• Code must be multithreaded-safe.
• Threads should not block each other for extended
periods of time.

Beyond CGI: Developing Java Servlets Module 3, slide 12 of 27


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

SingleThreadModel
• Should be implemented in a servlet if a service should
not run multiple servlet service methods concurrently.
1 public class FormServlet extends HttpServlet implements SingleThreadModel {
2 ...
3 }

• Guarantees that multiple instances of the servlet are


created and individually called for each request.

Beyond CGI: Developing Java Servlets Module 3, slide 13 of 27


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

The destroy Method


• destroy method called when a service unloads a
servlet
• destroy should:
• Undo any initialization work
• Synchronize persistent state with current in-memory
state of servlet

Beyond CGI: Developing Java Servlets Module 3, slide 14 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example destroy
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 }

Beyond CGI: Developing Java Servlets Module 3, slide 15 of 27


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

An Example destroy Method


• Uninitialized using connection.close
• Exceptions written to log files
• Handling concurrency issues

Beyond CGI: Developing Java Servlets Module 3, slide 16 of 27


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

Handling Service Threads at Servlet


Termination
• Make sure all threads complete before destroy
completes
• Long-running service methods should periodically poll
• Create instance variable access methods
• Number of threads indicator
• Shutting down indicator

Beyond CGI: Developing Java Servlets Module 3, slide 17 of 27


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

Tasks in Handling Threads


• At service termination:
• Establish service counter, shutdown flag, and
associated access methods
• Call these access methods from the service routine
• Check the shutdown flag
• Set the shutdown flag

Beyond CGI: Developing Java Servlets Module 3, slide 18 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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

Beyond CGI: Developing Java Servlets Module 3, slide 19 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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
• Performing the check

Beyond CGI: Developing Java Servlets Module 3, slide 20 of 27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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

Beyond CGI: Developing Java Servlets Module 3, slide 21 of 27


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

Review of Servlet Life Cycle


• Loading servlets using a class loader
• Overriding init and providing initialization
information to a servlet
• init called only once.
• init cannot be reloaded.
• Servlet receives client requests as soon as init
returns.
• There are no concurrency issues.

Beyond CGI: Developing Java Servlets Module 3, slide 22 of 27


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

Review of Servlet Life Cycle


• Accepting ServletConfig objects that have methods
for extracting initialization parameters
• Configuring initialization parameters (differs among
Web servers)
• Attending to thread-safe concurrency issues in servlet
service routine
• Implementing the SingleThreadModel interface
• Undoing initialization work and synchronizing
persistent state in the destroy method
• Attending to thread-safe concurrency issues before a
servlet is destroyed
Beyond CGI: Developing Java Servlets Module 3, slide 23 of 27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Exercise: Modifying the Form-


Processing Servlet
• Exercise objective: Modify servlet to accept file name
and directory to save form information, and ensure it
handles long-running threads
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Create BasicFormTwo.java
• Configure and invoke BasicFormTwo.java
• Exercise summary

Beyond CGI: Developing Java Servlets Module 3, slide 24 of 27


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

Check Your Progress


• List the four steps in a servlet’s lifecycle
• 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

Beyond CGI: Developing Java Servlets Module 3, slide 25 of 27


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

Check Your Progress


• 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

Beyond CGI: Developing Java Servlets Module 3, slide 26 of 27


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

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

Beyond CGI: Developing Java Servlets Module 3, slide 27 of 27


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

Module 4

Database Access

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 4, slide 2 of 33


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

Distributed Models
• Computations running in different address spaces
communicate.
• Two-tier (client/server) consists of multiple clients
talking to one or more servers.
• Multi-tier consists of multiple clients interacting with
one or more servers, which interact with one or more
additional servers.

Beyond CGI: Developing Java Servlets Module 4, slide 3 of 33


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

Distributed Java Technologies


• Java Database Connectivity (JDBC)
• Java Remote Method Invocation (RMI)
• Common Object Request Broker Architecture (CORBA)
represented by Java Interface Definition Language
(IDL)

Beyond CGI: Developing Java Servlets Module 4, slide 4 of 33


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

Java Database Connectivity (JDBC)


• Insulates Java client program from databases
• Provides generic interface classes that are implemented
by database-specific drivers

Beyond CGI: Developing Java Servlets Module 4, slide 5 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Database
Servlet
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, IOEx-
ception {
29
30 String lname;
31 Connection con = null;
32 PrintStream out = null;

Beyond CGI: Developing Java Servlets Module 4, slide 6 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Database
Servlet
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 7 of 33


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

Loading the Database Driver


• use Class.forName in java.lang
• Example uses:
Class.forName(jdbcclass).newInstance()

Beyond CGI: Developing Java Servlets Module 4, slide 8 of 33


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

Establishing a Connection to the


Database
• Need a connection to the database after the driver is
loaded
• Use DriverManager.getConnection in
java.sql.DriverManager
• URL for the driver
• user ID
• password
con = DriverManager.getConnection(url);

Beyond CGI: Developing Java Servlets Module 4, slide 9 of 33


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

Creating and Executing a Query


1 Statement stmt = con.createStatement();
2 String query = "SELECT first_name, last_name, comment "
+ "FROM emp_details " + "WHERE last_name='"+ lname +"'";
3
4 ResultSet rs = stmt.executeQuery(query);

Beyond CGI: Developing Java Servlets Module 4, slide 10 of 33


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

Parsing and Displaying the Results


• ResultSetMetaData object:
• Provides information about ResultSet object
• Provides information about the result data
• Provides schema information

Beyond CGI: Developing Java Servlets Module 4, slide 11 of 33


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

Closing the Connection


• Close a connection when it is no longer needed
con.close();

Beyond CGI: Developing Java Servlets Module 4, slide 12 of 33


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

JDBC and Servlets


• Establishing a database connection takes one to three
seconds.
• Creating a new connection for each request is
inefficient.
• Dealing with multiple users accessing the same data
poses concurrency issues.

Beyond CGI: Developing Java Servlets Module 4, slide 13 of 33


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

Connection Pools
• Timing and connection problem solved by creating pool
of persistent connections
• Pool managed by connection pool object:
• Manages set of connections
• Watches for locked or corrupted connections
• Performs housekeeping tasks
• Logs events

Beyond CGI: Developing Java Servlets Module 4, slide 14 of 33


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

Items to Consider
• Detecting and recovering from failures
• Determining the number of connections to create
• Deciding whether to allow blocking
• Deciding whether to log events and errors

Beyond CGI: Developing Java Servlets Module 4, slide 15 of 33


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

Implementing a Connection Pool


• Two components of a basic connection servlet solution:
• Servlet (connection pool client)
• Connection pool

Beyond CGI: Developing Java Servlets Module 4, slide 16 of 33


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

A Connection Pool Client


• Connection pool and connection pool servlet are middle
tier.
• Servlet’s service routine:

• Requests a connection from the pool

• Uses the connection to initiate a query


• Returns the connection

Beyond CGI: Developing Java Servlets Module 4, slide 17 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Connection
Pool Client Servlet
1 // Load the JDBC driver
2
3 // Instantiate a connection pool
4 ConnectionPool cp = new ConnectionPool(url, user, pass, ini-
tialCons, 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();

Beyond CGI: Developing Java Servlets Module 4, slide 18 of 33


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

The ConnectionPool API


• Accomplishes some of the basic database tasks: creating
and closing connections

Beyond CGI: Developing Java Servlets Module 4, slide 19 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The ConnectionPool
Constructor
1 public ConnectionPool(String url, String user, String pass-
word,
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 20 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The addConnection
Method
1 private void addConnection() throws SQLException {
2 free.addElement(getNewConnection());
3 }

Beyond CGI: Developing Java Servlets Module 4, slide 21 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The getNewConnection
Method
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 22 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The getConnection
Method
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 wait-
ing?
14 if (free.isEmpty()) {
15 if (maxCons <= 0 || numCons < maxCons) {
16 addConnection();
17 } else {
18 throw new SQLException("Timeout waiting for a con-
nection 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 con-
nections reached");
24 }

Beyond CGI: Developing Java Servlets Module 4, slide 23 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The getConnection
Method
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 24 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The releaseConnection
Method
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 25 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The releaseConnection
Method
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 26 of 33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The closeAll Method
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 }

Beyond CGI: Developing Java Servlets Module 4, slide 27 of 33


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

Review of Database Access


• Database client:
• Loads the database driver
• Establishes a connection
• Creates and executes a query
• Parses and displays the results
• Closes the connection

Beyond CGI: Developing Java Servlets Module 4, slide 28 of 33


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

Review of Database Access


• A connection pool improves database access times and
consists of:
• A constructor ConnectionPool
• A method getConnection
• A method releaseConnection
• A method closeAll

Beyond CGI: Developing Java Servlets Module 4, slide 29 of 33


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

Exercise: Enhancing a Database Servlet


• Exercise: Modifying a database servlet to use a
connection manager and be thread safe
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Modifying DBServlet to use a connection pool
• Log client’s IP address, getConnection call, and
releaseConnection call
• (Optional) Use initialization parameters for database
URL
• Exercise summary

Beyond CGI: Developing Java Servlets Module 4, slide 30 of 33


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

Check Your Progress


• 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

Beyond CGI: Developing Java Servlets Module 4, slide 31 of 33


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

Check Your Progress


• List the basic APIs necessary in a connection pool class
• Update the DBServlet to implement connection
management, quick database access, and thread safety

Beyond CGI: Developing Java Servlets Module 4, slide 32 of 33


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

Think Beyond
What are some additional database-related modifications that
might be added to a connection pool?

Beyond CGI: Developing Java Servlets Module 4, slide 33 of 33


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

Module 5

RMI and CORBA/IDL

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 5, slide 2 of 26


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

Java RMI
• Allows access to remote objects on other JVMs
• RMI solution has three parts:

• Server

• Client
• RMI registry

Beyond CGI: Developing Java Servlets Module 5, slide 3 of 26


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

Interaction Between 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

Beyond CGI: Developing Java Servlets Module 5, slide 4 of 26


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

Implementing a Basic RMI Server


1. Create a remote interface
2. Develop an implementation of the remote interface
3. Instantiate the remote object
4. Register a remote object stub with the RMI registry

Beyond CGI: Developing Java Servlets Module 5, slide 5 of 26


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

Implementing a Basic RMI Client


1. Use RMI Naming services to look up and create a
remote object stub from the RMI registry
2. Invoke the remote object’s methods via the stub

Beyond CGI: Developing Java Servlets Module 5, slide 6 of 26


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

Installing and Invoking the Server,


Client, and RMI Registry
1. Place interface class on client and server
2. Place remote object implementation on server
3. Generate stubs and skeletons with rmic
4. Put stubs on client and put skeletons on server
5. Start the RMI registry
6. Start the RMI server program
7. Start the RMI client program

Beyond CGI: Developing Java Servlets Module 5, slide 7 of 26


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

RMI and Servlets


• Servlet can be RMI client or server

Beyond CGI: Developing Java Servlets Module 5, slide 8 of 26


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

An Example RMI Servlet Solution


• Servlet is an RMI client accessing a remote database
object.
• Example uses an applet to invoke the servlet.

Beyond CGI: Developing Java Servlets Module 5, slide 9 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Server
• 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 }

• Remote interface to the database object

Beyond CGI: Developing Java Servlets Module 5, slide 10 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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 imple-
ments 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 // 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

Beyond CGI: Developing Java Servlets Module 5, slide 11 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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 }
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, our 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

Beyond CGI: Developing Java Servlets Module 5, slide 12 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Server
• DatabaseImpl.java
50
51 /****************************************************************
52 * getClientVisits returns a Vector of Strings, each of which
53 * represents a visit.
54 *****************************************************************/
55 public Vector getClientVisits(String ip_addr)
throws RemoteException
56 {
57 ...
58 }
59
60 /******************************************************************
61 * getNumberOfVisitors calculates the total number of visitors in
62 * the database.
63 ******************************************************************/
64 public long getNumberOfVisitors() throws RemoteException
65 {
66 ...
67 }

Beyond CGI: Developing Java Servlets Module 5, slide 13 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
/An Example RMI Server
• DatabaseImpl.java
68
69 /******************************************************************
70 * getNumberOfClientVisits calculates the number of times a client
71 * with the given String interacted with our service.
72
*******************************************************************/
73 public long getNumberOfClientVisits(String ip_addr)
throws RemoteException
74 {
75 ...
76 }
77
78 public void close() throws RemoteException
79 {
80 ...
81 }
82 }

• The implementation of the remote


object interface

Beyond CGI: Developing Java Servlets Module 5, slide 14 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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 }

• Creates remote object


• Registers remote object stub with RMI
registry

Beyond CGI: Developing Java Servlets Module 5, slide 15 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Client
• ClientLogServlet
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 ServletExcep-
tion
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(remoteObj-
Param);
31 System.err.println("remoteObjParam: "+remoteObject-
Name);
32

Beyond CGI: Developing Java Servlets Module 5, slide 16 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Client
• ClientLogServlet
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");

Beyond CGI: Developing Java Servlets Module 5, slide 17 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Client
• ClientLogServlet
62 ObjectOutputStream oos = new
ObjectOutputStream(r sOut);
63 System.err.println("got object output stream");
64 String clientInetAddr = req.getRemoteAddr();
65 System.err.println("got clientIntAddr: " + clientIne-
tAddr);
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 {

Beyond CGI: Developing Java Servlets Module 5, slide 18 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Client
• ClientLogServlet
92 try
93 {
94 database.close();
95 }
96 catch(Exception e)
97 {
98 System.exit(0);
99 }
100 }
101 }

• Uses Naming lookup to obtain a


remote object stub instance

• Calls methods of remote object via


stub instance

Beyond CGI: Developing Java Servlets Module 5, slide 19 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Applet
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);

Beyond CGI: Developing Java Servlets Module 5, slide 20 of 26


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example RMI Applet
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 }
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 }

Beyond CGI: Developing Java Servlets Module 5, slide 21 of 26


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

Java IDL
• Allows access to remote objects
• Uses an object request broker (ORB)
• May be implemented via servlets
• Not platform independant
• Cannot move (serialize) objects

Beyond CGI: Developing Java Servlets Module 5, slide 22 of 26


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

Review of RMI and CORBA/IDL


• RMI applications consist of three components:

• Server

• Client

• RMI registry

• CORBA/IDL provides functionality similar to RMI

• CORBA/IDL and RMI can be used with servlets

Beyond CGI: Developing Java Servlets Module 5, slide 23 of 26


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

Exercise: Configuring and Invoking


the RMI Example
• Exercise objective: Configure and run the example

• Preparation: See documentation in Appendix B and at


http://host_name:8080/system/doc/index.html
• Tasks

• Configure the RMI example

• Invoke the RMI example

• Exercise summary

Beyond CGI: Developing Java Servlets Module 5, slide 24 of 26


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

Check Your Progress


• Define the purpose of RMI

• Identify four items for implementing RMI server


• Identify two items for implementing RMI client
• Identify six steps to install and invoke RMI client and
server
• List two differences between RMI and CORBA/IDL
• Configure and invoke an example RMI servlet solution

Beyond CGI: Developing Java Servlets Module 5, slide 25 of 26


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

Think Beyond
Are there any additional distributed technologies that can be
used with servlets?

Beyond CGI: Developing Java Servlets Module 5, slide 26 of 26


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

Module 6

Persistent State in HTTP Servlets

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 6, slide 2 of 25


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

Benefits and Limitations of


Statelessness in the HTTP Protocol
• HTTP transactions are stateless.
• Benefit – Client browsers do not notice when a server
goes down and comes up quickly.
• Drawback – It is difficult to produce groups of pages for
collecting information to produce picture of the user’s
experience.

Beyond CGI: Developing Java Servlets Module 6, slide 3 of 25


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

Demonstrating the Benefits of State


• Authentication Web page gathers user authentication
information.
• A database Web page controls access to database data
after authentication.

Beyond CGI: Developing Java Servlets Module 6, slide 4 of 25


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

Cookies
• Cookies are a mechanism for storing a variable and its
associated value on the browser.

• Server requests that a cookie value be set.

• Browser accepts or declines the cookie.


• Acceptance of cookie is user configurable.

Beyond CGI: Developing Java Servlets Module 6, slide 5 of 25


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

Programming With Cookies


• Using cookies in a servlet is simple.
• Servlet API enables you to:
• Set a cookie
• Get a cookie
• Sessions should be used in new development instead of
cookies.

Beyond CGI: Developing Java Servlets Module 6, slide 6 of 25


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

Setting a Cookie
1. Create the cookie:
Cookie c = new Cookie("MyName", "MyValue");

2. Set the cookie:


resp.addCookie(c);

Beyond CGI: Developing Java Servlets Module 6, slide 7 of 25


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

Retrieving 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 }

Beyond CGI: Developing Java Servlets Module 6, slide 8 of 25


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

Sessions
• A collection of related HTTP transactions made by one
browser to one server.
• Or, a collection of data associated with those
transactions, which is made available to servlets
invoked by the browser.
• Supported by the interface
javax.servlet.http.HttpSession.

Beyond CGI: Developing Java Servlets Module 6, slide 9 of 25


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

The HttpSession Interface


• Web server developer provides a class that implements
this interface.
• All programming is done using the interface, not the
implementation class.
• There are two methods in the HttpSession interface:
• getValue
• putValue
• Sessions can store and access information of any kind.

Beyond CGI: Developing Java Servlets Module 6, slide 10 of 25


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

Example
• Two servlets:
• Login servlet
• Secret servlet

Beyond CGI: Developing Java Servlets Module 6, slide 11 of 25


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

The Login Servlet


• Collects user name and password from POST request
• Validates user data
• Creates and initializes an HttpSession
• Provides an init and doPost method

Beyond CGI: Developing Java Servlets Module 6, slide 12 of 25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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

Beyond CGI: Developing Java Servlets Module 6, slide 13 of 25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
The Login Servlet: doPost
Method
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 }

Beyond CGI: Developing Java Servlets Module 6, slide 14 of 25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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 }

Beyond CGI: Developing Java Servlets Module 6, slide 15 of 25


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

The Secret Servlet


• Checks for the existence of the session
• Returns an error report if session not found
• Generates a dynamic Web page with secret information

Beyond CGI: Developing Java Servlets Module 6, slide 16 of 25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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 }

Beyond CGI: Developing Java Servlets Module 6, slide 17 of 25


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

Additional Guidelines
• Servlets must create sessions.
• Servlets can determine if a session exists:
• getSession(false) or getSession(true)
• Any servlet can request that a session be created.
• Information in a session is available to all servlets
handling the target browser.
• Sessions can be invalidated (session.invalidate).
• Sessions can time out and become invalid due to
browser inactivity.

Beyond CGI: Developing Java Servlets Module 6, slide 18 of 25


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

Tying a Session to a Browser


• Cookies
• Track sessions relating to browsers
• Are not supported by some browsers
• Are not used by some users for security reasons
• URL rewriting
• Ties a session to a browser by adding a session ID to
a requested URL
• Consumes time for page scanning and URL rewriting
• Uses encodeURL and encodeRedirectURL

Beyond CGI: Developing Java Servlets Module 6, slide 19 of 25


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

Cookies and Sessions Compared


• Cookies are often disabled by browser users.
• Cookies store one piece of information at a time.
• Different versions of the cookie specification exists.
• Cookie space may be limited on the client.

Beyond CGI: Developing Java Servlets Module 6, slide 20 of 25


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

Review of Cookies and Sessions


• Cookies store a variable and its associated value in the
browser.
• Cookies are user configurable within a browser.
• Not all browsers support cookies.
• Cookies are accessible using addCookie and getCookie
methods.

Beyond CGI: Developing Java Servlets Module 6, slide 21 of 25


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

Review of Cookies and Sessions


• A session is a collection of data associated with
transactions made between a browser and a Web server.
• Servlets must create sessions before they are accessible.
• The following methods exist for session development:
• getSession
• putValue(key, value)
• getValue(key)
• URL rewriting can be used to track a session.
• encodeURL and encodeRedirectURL

Beyond CGI: Developing Java Servlets Module 6, slide 22 of 25


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

Exercise: Developing a Web Shopping


Solution
• Exercise objective: Create two servlets that will use
sessions in a shopping solution
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Create and invoke a ShopLogin servlet
• Create and invoke a ShopBuy servlet
• Enhance the ShopBuy Servlet
• Exercise summary
Beyond CGI: Developing Java Servlets Module 6, slide 23 of 25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Check Your Progress


• 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)

Beyond CGI: Developing Java Servlets Module 6, slide 24 of 25


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

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?

Beyond CGI: Developing Java Servlets Module 6, slide 25 of 25


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

Module 7

Time-Extended Connections

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 7, slide 2 of 13


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

What Is a Time-Extended Connection?


• HTTP transfer mechanism sends static pages.
• Information is updated when user requests new
page.
• Some situations require automatic update of Web pages
• This requires a special connection called time-
extended connection.

Beyond CGI: Developing Java Servlets Module 7, slide 3 of 13


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

Implementation Options
• Client pull and server push
• Efficiency of client pull and server push
• Polling rates
• Server push is more efficient than client pull
• Options described in this module:
• Dynamic updates using HTML
• Continuous or transient TCP connections
• User datagram protocol (UDP)
• Broadcast and multicast connections

Beyond CGI: Developing Java Servlets Module 7, slide 4 of 13


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

HTML and Dynamic Updates


• HTML extensions can implement client pull or server
push.
• JavaScript™ enables automatically display of a new
page after a period of time.
• HTTP connections can be made to remain open for an
extended period of time.

Beyond CGI: Developing Java Servlets Module 7, slide 5 of 13


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

Java Technology and Dynamic


Updates
• Java programming language offers additional solutions:
• Example: Implement client pull with an applet

Beyond CGI: Developing Java Servlets Module 7, slide 6 of 13


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

Continuous or Transient TCP


Connections
• Transmission control protocol (TCP)
• TCP is a connection-oriented transmission protocol.
• Connection is required before a message can be sent.
• Connection is established by creating a unique server
and client socket.
• As time-extended connection, sockets exist until no
longer needed by the client.
• TCP can cause many connections on the Web server
that utilize resources for long periods of time.

Beyond CGI: Developing Java Servlets Module 7, slide 7 of 13


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

User Datagram Protocol


• Connection not required before sending a message.
• Each client does not require a separate connection at the
server.
• Solves scalability issues
• Is not reliable
• Mechanisms can be designed to determine if messages
have been missed.

Beyond CGI: Developing Java Servlets Module 7, slide 8 of 13


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

Broadcast and Multicast Connections


• With UDP, datagrams can be sent to multiple recipients
• Options for handling multiple recipients:
• Broadcast message – Sent to a special IP address
• Multicast message – Sent to a special group IP
address

Beyond CGI: Developing Java Servlets Module 7, slide 9 of 13


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

Review of Time-Extended
Connections
• Are either client pull or server push
• Client pull connections are inefficient
• Four time-extended implementation options
• Dynamic updates using HTML
• Continuous or transient TCP connections
• User datagram protocol (UDP)
• Broadcast or multicast connections

Beyond CGI: Developing Java Servlets Module 7, slide 10 of 13


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

Exercise: Developing a UDP Broadcast


Transaction Monitor
• Exercise objective: Use a time-extended connection to
monitor activity in the shopping servlet
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks

• Create a UDP transaction monitor

• Exercise summary

Beyond CGI: Developing Java Servlets Module 7, slide 11 of 13


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

Check Your Progress


• Define the term time-extended connection
• Identify the difference between client pull and server
push
• List four options for maintaining a time-extended
connection and outline the strengths and/or
weaknesses of each
• Develop a UDP transaction monitor servlet

Beyond CGI: Developing Java Servlets Module 7, slide 12 of 13


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

Think Beyond
Can you see security implications in broadcasting or
multicasting?
Consider how each of the various time-extended connection
options would respond to a temporary network failure. Do
they simply recover if the network recovers, or do they need
recovery code? Do they hang up if a receiving station fails?

Beyond CGI: Developing Java Servlets Module 7, slide 13 of 13


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

Module 8

Servlet Security

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 8, slide 2 of 22


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

Major Threats to Web Server Security


• Theft or alteration of data
• Malicious code
• Eavesdropping

Beyond CGI: Developing Java Servlets Module 8, slide 3 of 22


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

Authentication and Authorization


• Authentication: determining who is requesting access
• Authorization: determining what access a user has to
resources
• Authentication mechanism overview
• Passphrase authentication
• Challenge-response
• Public key protocol
• Authorization process overview

Beyond CGI: Developing Java Servlets Module 8, slide 4 of 22


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

Types of HTTP Authentication


• Basic authentication
• Uses user name/password
• Supported through access control lists (ACLs)
• Not very secure: sends passwords as "clear text"
• Digest authentication
• Full passwords not sent over the wire
• Secure sockets layer (SSL) server authentication
• Establishes authentication between client and server

Beyond CGI: Developing Java Servlets Module 8, slide 5 of 22


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

Security Realms
• Contain users, groups, and their ACLs
• Realms in Java Web Server
• UNIXRealm
• NTRealm
• defaultRealm
• CertificateRealm
• servletMgrRealm
• SharedPasswordRealm

Beyond CGI: Developing Java Servlets Module 8, slide 6 of 22


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

Basic HTTP Authentication In-Depth


1. Browser sends URL.
2. Server determines whether page is protected.
3. Web server checks for non-null authorization header,
sends challenge.
4. Browser interprets 401 error as challenge.
5. Dialog box prompts for user name and password.
6. Browser returns encoded authentication information.
7. Server validates authentication information, returns
page.

Beyond CGI: Developing Java Servlets Module 8, slide 7 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
Basic HTTP Authentication
In-Depth
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

Beyond CGI: Developing Java Servlets Module 8, slide 8 of 22


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

Implementing Basic Authentication in


a Servlet
1. Request is made to a URL.
2. URL is resolved to BasicAuth servlet.
3. Servlet checks for user name and password.
4. If null, a 401 error is returned.
5. Browser receives user name and password.
6. Browser calls doGet with base64-encoded user:pass.
7. User name and password decoded and checked for
validity.

Beyond CGI: Developing Java Servlets Module 8, slide 9 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Basic
Authentication Servlet
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 ();

Beyond CGI: Developing Java Servlets Module 8, slide 10 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Basic
Authentication Servlet
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

Beyond CGI: Developing Java Servlets Module 8, slide 11 of 22


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

Examples of Server-Independent
Validation
• Access through JDBC, ODMG2, Enterprise Bean
• Access through middle tier: RMI, CORBA/IIOP, Java
IDL
• Flat file password lookup
• Assigning "one-time" password
• Performing translation between legacy system and Java
program

Beyond CGI: Developing Java Servlets Module 8, slide 12 of 22


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

Additional Security Features of Java


Web Server
• Secure administration
• Servlet sandbox

Beyond CGI: Developing Java Servlets Module 8, slide 13 of 22


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

Secure Administration With SSL


• Public key certificates are used to identify clients.
• Data is encrypted.
• Data is protected for integrity.
• Clients can use their own public keys to authenticate to
your server.

Beyond CGI: Developing Java Servlets Module 8, slide 14 of 22


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

Servlet Sandbox
• Remote servlets are untrusted.

• Each untrusted servlet thread is contained within a


sandbox.
• The servlet sandbox protects files, runtime state,
administrative state, network servers, and other
Security Manager resources.

Beyond CGI: Developing Java Servlets Module 8, slide 15 of 22


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

Servlet Types
• Trusted servlets
• Java Web Server-internal servlets
• Local servlets
• Signed network servlets
• Unsigned network servlets

Beyond CGI: Developing Java Servlets Module 8, slide 16 of 22


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

RemoteUser Property
• Set by the Web server upon authentication
• Can be used to detect whether a user has authenticated
• Can be used in conjunction with sessions
• Can be checked using getRemoteUser

Beyond CGI: Developing Java Servlets Module 8, slide 17 of 22


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

Sanity Checking
• You will know the parameters a servlet will receive.
• Check all request parameters that access volatile data
for validity.

Beyond CGI: Developing Java Servlets Module 8, slide 18 of 22


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

Review of Servlet Security


• Basic authentication
• Digest authentication
• SSL server authentication
• Realms
• Seven steps of basic HTTP authentication
• SSL and servlet sandboxing
• Untrusted, trusted, and signed network servlets
• RemoteUser property

Beyond CGI: Developing Java Servlets Module 8, slide 19 of 22


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

Exercise: Basic and Certificate


Authentication Servlets
• Exercise objectives: Create a servlet to do basic
authentication, and examine certificate authority
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Create a basic authentication servlet
• Investigate a certificate authority servlet
• (Optional) Browse the RFCs
• Exercise summary
Beyond CGI: Developing Java Servlets Module 8, slide 20 of 22
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Check Your Progress


• Identify the three major threats to Web server security
• Explain the three HTTP security mechanisms supported
by 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 access authentication

Beyond CGI: Developing Java Servlets Module 8, slide 21 of 22


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

Think Beyond
How might security be implemented in the exercises used
throughout this course?

Beyond CGI: Developing Java Servlets Module 8, slide 22 of 22


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

Module 9

Servlet Beans

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 9, slide 2 of 21


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

What Is JavaBeans?
• Portable, platform-independent component model
• Written in the Java programming language
• Beans
• Reusable software pieces
• Combined to create application or applet

Beyond CGI: Developing Java Servlets Module 9, slide 3 of 21


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

Functionality of Beans
• Introspectable
• Event aware
• Customizable
• Persistent

Beyond CGI: Developing Java Servlets Module 9, slide 4 of 21


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

What Is a Servlet Bean?


• A servlet that adheres to the JavaBeans design patterns,
particularly introspection.

Beyond CGI: Developing Java Servlets Module 9, slide 5 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example 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 }

Beyond CGI: Developing Java Servlets Module 9, slide 6 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Servlet Bean
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> val-
ue.
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> val-
ue.
56 * @return The new value for that property
57 */
58 public void setIntProperty(int intProperty){
59 this.intProperty = intProperty;
60 }
61 }

Beyond CGI: Developing Java Servlets Module 9, slide 7 of 21


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

Setting Header Information


• res.setHeader – Add field to response header with a
given name and value
• Setting cache-control
• Cache-Control header field
• no-cache attribute

Beyond CGI: Developing Java Servlets Module 9, slide 8 of 21


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

get and set Accessor and Mutator


Methods
• Properties in ServletConfig
• Introspected properties
• Properties discovered and identified by their get and
set methods.
• Example contains two properties: stringProperty
and intProperty.

Beyond CGI: Developing Java Servlets Module 9, slide 9 of 21


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

Servlet Beans Persistence


• Implementing java.io.Serializable or
java.io.Externalizable
• Writing to a serialization file (.ser) file

Beyond CGI: Developing Java Servlets Module 9, slide 10 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example of Writing to a
Serialization File
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 }

• ObjectOutputStream and
ObjectOutput classes
• writeObject method

Beyond CGI: Developing Java Servlets Module 9, slide 11 of 21


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

Packaging Servlet Beans


• JAR files containing serialized Beans (.ser) files
• Generating a serialized Bean

Beyond CGI: Developing Java Servlets Module 9, slide 12 of 21


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

Servlet Bean Instantiation


• Class loader for deserializing Bean files
• Locations for servlet Beans
• Automatic reloading of servlet Beans

Beyond CGI: Developing Java Servlets Module 9, slide 13 of 21


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

Invoking Servlet Beans


• Invoked the same way as any other servlet
• Accessing servlet Bean using a URL:
• Use servlet/ URL
http://host_name:port/servlet/ServletName

Beyond CGI: Developing Java Servlets Module 9, slide 14 of 21


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

An Example of Invoking a Servlet Bean


Using a URL
server_root/

... servletbeans/ ...


Hello.jar
Hello.class
hello1.ser
hello2.ser

Counter.class
counter1.ser

Beyond CGI: Developing Java Servlets Module 9, slide 15 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example of Invoking a
Servlet Bean Using a URL
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 }

Beyond CGI: Developing Java Servlets Module 9, slide 16 of 21


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

An Example of Invoking a Servlet Bean


Using a URL
• http://host_name:port/servlet/hello1

• http://host_name:port/servlet/hello2
• http://host_name:port/servlet/Hello

Beyond CGI: Developing Java Servlets Module 9, slide 17 of 21


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

Review of Servlet Beans


• Automatically recognizing properties through
introspection
• Implementing java.io.Serializable or
java.io.Externalizable
• Packaging servlet Beans in JAR files
• Creating serialized forms of servlet Beans
• Placing servlet Beans in server_root/servletbeans
• Invoking servlet Beans

Beyond CGI: Developing Java Servlets Module 9, slide 18 of 21


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

Exercise: Creating a Servlet Bean


• Exercise objective: Create a servlet Bean utilizing
standard functionality
• Preparation: See documentation in Appendix B and at
http://host_name:8080/system/doc/index.html
• Tasks
• Create a CounterBean servlet Bean
• Test the CounterBean servlet Bean
• Implement servlet Bean persistence
• Create an advanced counter servlet Bean
• Exercise summary
Beyond CGI: Developing Java Servlets Module 9, slide 19 of 21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Check Your Progress


• 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

Beyond CGI: Developing Java Servlets Module 9, slide 20 of 21


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

Think Beyond
How might you use the JavaBeans event mechanism to extend
the functionality of your servlet Beans?

Beyond CGI: Developing Java Servlets Module 9, slide 21 of 21


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

Module 10

Dynamic Web Content

Beyond CGI: Developing Java Servlets October 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

Beyond CGI: Developing Java Servlets Module 10, slide 2 of 30


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

Generating Dynamic Content


• CGI
• Servlets
• JavaServer Pages™ (JSP)

Beyond CGI: Developing Java Servlets Module 10, slide 3 of 30


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

CGI print Statements


print "<HTML><HEAD><TITLE>Hello World</TITLE>

</HEAD><BODY><h1>Hello World</h1></BODY></HTML>";

Beyond CGI: Developing Java Servlets Module 10, slide 4 of 30


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

Servlet println Statements


24 out.println("<HEAD><TITLE>Howdy Servlet</TITLE></HEAD>");
25 out.println("<BODY>");
26 out.println("Howdy " + getParameter("yourname"));
27 out.println("</BODY>");
28 out.close();

Beyond CGI: Developing Java Servlets Module 10, slide 5 of 30


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

Servlet println and Perl print


Statements
• Shortcomings
• Prevents reuse of code (HTML and Java or script
code combined in a servlet)
• Forces HTML experts and developers of Perl or Java
technology to learn particulars of each other’s jobs

Beyond CGI: Developing Java Servlets Module 10, slide 6 of 30


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

JavaServer Pages
• Web pages containing a combination of HTML and
code
• Benefits of using JSP

• Cleanly separate presentation from content

• Are automatically recompiled when source file


changes

Beyond CGI: Developing Java Servlets Module 10, slide 7 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Java Server
Page
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
19 Back button and fill in the empty fields in your form.
20 <%} else {
21 String foo = request.getParameter("first");
22 out.println(foo);%>
23 <%}
24 } %>

Beyond CGI: Developing Java Servlets Module 10, slide 8 of 30


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

JavaServer Pages Syntax


• Directives
• Declarations
• Scriptlets
• Expressions
• Bean tags

Beyond CGI: Developing Java Servlets Module 10, slide 9 of 30


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

Directives
• language tag
<%@ language = "java" %>
• method variable
<%@ method = "doPost" %>
• import variable
<%@ import = "java.io.*,java.util.Hashtable" %>
• implements variable
<%@ implements = "SingleThreadModel" %>
• extends variable
<%@ extends = "javax.servlet.http.HttpServlet" %>

Beyond CGI: Developing Java Servlets Module 10, slide 10 of 30


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

Declarations
• SCRIPT tags
<SCRIPT runat=server>

</SCRIPT>

• An example JavaServer page declaration:


< SCRIPT runat=server >

int i = 0;

String foo = "Hello";

private void foo() {

// some code;

< /SCRIPT >

Beyond CGI: Developing Java Servlets Module 10, slide 11 of 30


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

Scriptlets
• A portion of scripting code providing additional
functionality to HTML

• <% and %> tags


• request
• response
• out
• in

Beyond CGI: Developing Java Servlets Module 10, slide 12 of 30


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

Expressions
• Are variables substituted with values after the value is
resolved.
• Are defined within <%= and %>
• Example JavaServer page expression:
<% int number = 20;

int i = number + 1; %>

<p>

The result of the computation is:<% =i %>

Beyond CGI: Developing Java Servlets Module 10, slide 13 of 30


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

Additional Guidelines
• Many scriptlet blocks are possible.
• Variables declared in one block are visible in
subsequent blocks.
• Conditional statements can be used to determine
printing.

Beyond CGI: Developing Java Servlets Module 10, slide 14 of 30


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

The <BEAN> Tag


• Enables accessing any Java object from within a
JavaServer page

Beyond CGI: Developing Java Servlets Module 10, slide 15 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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> Guess them both right and your browser foreground/back-
ground
21 will change to my two favorite colors to display this page.
22
23 <p> If you guess one of them right, either your foreground or
24 your background will change to the color that was guessed
right.
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

Beyond CGI: Developing Java Servlets Module 10, slide 16 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example JavaServer
Page Using the <BEAN> Tag
33 <% if (cb.getSuccess()) { %>
34 <% cb.reset(); %>
35
36 <p> CONGRATULATIONS!!
37 <p> You guessed in <%= cb.getAttempts() %> attempts!
38
39 <% if (cb.gotHints()) { %>
40
41 <p> ( although I know you cheated and peeked into 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 <p>
59
60 </font>
61 </body>
62 </html>
63

Beyond CGI: Developing Java Servlets Module 10, slide 17 of 30


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

Declaring a Bean
• BEAN tag syntax
< BEAN name="value" varname="value" class="name"
introspect="no"

serializedfile="value" create=”no"
scope="request">

• name
• varname
• type
• introspect

Beyond CGI: Developing Java Servlets Module 10, slide 18 of 30


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

Declaring a Bean
• create
• scope
• request
• session
• beanName

Beyond CGI: Developing Java Servlets Module 10, slide 19 of 30


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

PageCompileServlet
• Invoked when client requests a JavaServer page
• Loaded and initialized as any other servlet
• Compiles JSP files into servlets

Beyond CGI: Developing Java Servlets Module 10, slide 20 of 30


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

PageCompileServlet

Beyond CGI: Developing Java Servlets Module 10, slide 21 of 30


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

An Example 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>

Beyond CGI: Developing Java Servlets Module 10, slide 22 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
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.ParamsHttpServle-
tRequest;
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,IOEx-
ception {
21 ServletOutputStream out = response.getOutputStream ();
22 ByteFileData __fileData = null;
23
24 try {

Beyond CGI: Developing Java Servlets Module 10, slide 23 of 30


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services
An Example Servlet
Created From a JavaServer
Page
25 __fileData = (ByteFileData)
26 ServletUtil.getFileCache(this).getFile("
C:\\Java Web Server1.0\\public_html\\FirstPage.jht-
ml",
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 }

Beyond CGI: Developing Java Servlets Module 10, slide 24 of 30


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

Creating a Servlet from a JavaServer


Page
• JavaServer page’s scriptlet code and HTML code are
placed in servlet’s service routine
• HTML code is written to a stream

Beyond CGI: Developing Java Servlets Module 10, slide 25 of 30


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

Review of JavaServer Pages


• Directives: language, method, import, implements,
extends
• Declarations
• Scriptlets – <% and %>
• Expressions

Beyond CGI: Developing Java Servlets Module 10, slide 26 of 30


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

Review of JavaServer Pages


• <BEAN> tags
• name
• varname
• type
• introspect
• create
• scope
• beanName
• PageCompileServlet

Beyond CGI: Developing Java Servlets Module 10, slide 27 of 30


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

Exercise: Creating JavaServer Pages


• Exercise objective: Create two JavaServer pages
• Preparation:
• See documentation in Appendix B and at http://
host_name:8080/system/doc/index.html
• Copy files to server_root/classes/jsp/beans/
and server_root/public_html/ (see exercise)
• Tasks:
• Develop an ImageTableInfo JavaServer page
• Call the ImageTableBean from the ImageTable.jsp
JavaServer page
• Exercise summary
Beyond CGI: Developing Java Servlets Module 10, slide 28 of 30
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A
Sun Educational Services

Check Your Progress


• 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

Beyond CGI: Developing Java Servlets Module 10, slide 29 of 30


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

Think Beyond
How might you use JavaServer Pages on your Web site?

Beyond CGI: Developing Java Servlets Module 10, slide 30 of 30


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

About This Course .......................................................................................................Preface-1


Course Goal .................................................................................................................................. Preface-2
Course Overview ......................................................................................................................... Preface-3
Course Map ................................................................................................................................... Preface-4
Module-by-Module Overview ................................................................................................... Preface-5
Course Objectives ......................................................................................................................... Preface-7
Skills Gained by Module ............................................................................................................. Preface-9
Guidelines for Module Pacing ................................................................................................. Preface-10
Topics Not Covered ................................................................................................................... Preface-11
How Prepared Are You? ........................................................................................................... Preface-12
Introductions .............................................................................................................................. Preface-13
How to Use Course Materials .................................................................................................. Preface-14
Icons ............................................................................................................................................. Preface-15
Typographical Conventions ..................................................................................................... Preface-16

Servlet Basics ..........................................................................................................................1-1


Overview .................................................................................................................................................. 1-2
Common Gateway Interface (CGI) ....................................................................................................... 1-3
CGI Request and Response .................................................................................................................... 1-4
CGI and HTTP ......................................................................................................................................... 1-5
An Example HelloWorld CGI Script ................................................................................................... 1-6
Setting Content Type .............................................................................................................................. 1-7
Returning a Response ............................................................................................................................. 1-8
Invoking the Example CGI Script ......................................................................................................... 1-9
Web Server and CGI Support .............................................................................................................. 1-10
What Is a Servlet? .................................................................................................................................. 1-11

Beyond CGI: Developing Java Servlets xxxi


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

Servlet Request and Response ............................................................................................................. 1-12


HTTP and Servlets ................................................................................................................................ 1-13
An Example HelloWorld Servlet ........................................................................................................ 1-14
HttpServlet ............................................................................................................................................. 1-16
The service Method ............................................................................................................................... 1-17
Setting Content Type ............................................................................................................................ 1-18
Returning a Response ........................................................................................................................... 1-19
Writing Exceptions to Log Files .......................................................................................................... 1-20
Invoking the Example Servlet ............................................................................................................. 1-21
Web Server Servlet Support ................................................................................................................ 1-22
Review of Servlet Basics ....................................................................................................................... 1-23
Exercise: Developing a Simple HTTP Servlet ................................................................................... 1-24
Check Your Progress ............................................................................................................................ 1-25
Think Beyond ........................................................................................................................................ 1-26

Forms Processing With Servlets ...........................................................................................2-1


Overview .................................................................................................................................................. 2-2
A Basic Form Solution ............................................................................................................................ 2-3
The <FORM> Tag ....................................................................................................................................... 2-6
METHOD ...................................................................2-7
ACTION and ENCTYPE ........................................................2-8
The <INPUT> Tag ..................................................................................................................................... 2-9
An Example Form-Processing Script ................................................................................................. 2-10
Parsing the Request .............................................................................................................................. 2-13
Returning a Response ........................................................................................................................... 2-14
Invoking the Example Form-Processing Script ................................................................................ 2-15
Forms and Servlets ................................................................................................................................ 2-16
An Example Form-Processing Servlet ............................................................................................... 2-17
HTTPServlet Service Methods ............................................................................................................ 2-18
Setting Content Type ............................................................................................................................ 2-19

Beyond CGI: Developing Java Servlets xxxii


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

Parsing the Request .............................................................................................................................. 2-20


HTTP POSTs With Binary or Text (Localized) Data ......................................................................... 2-21
Returning a Response ........................................................................................................................... 2-22
Displaying Information About a Servlet ........................................................................................... 2-23
Invoking the Example Form-Processing Servlet .............................................................................. 2-24
Review of Form Servlets ...................................................................................................................... 2-25
Exercise: Developing Form-Processing Servlets ............................................................................... 2-27
Check Your Progress ............................................................................................................................ 2-28
Think Beyond ........................................................................................................................................ 2-30

Servlet Life Cycle ....................................................................................................................3-1


Overview .................................................................................................................................................. 3-2
Servlet Life Cycle .................................................................................................................................... 3-3
Loading and Instantiating a Servlet ..................................................................................................... 3-4
The init Method .................................................................................................................................... 3-5
An Example init Method ..................................................................................................................... 3-6
Configuring Initialization Parameters ................................................................................................. 3-8
The service Method ............................................................................................................................. 3-9
Multithreaded-Safe Servlets ................................................................................................................ 3-10
An Example Synchronized Access Method ...................................................................................... 3-11
Multithreaded-Hot Servlets ................................................................................................................. 3-12
SingleThreadModel .......................................................3-13
The destroy Method ........................................................................................................................... 3-14
An Example destroy Method ............................................................................................................ 3-15
Handling Service Threads at Servlet Termination ........................................................................... 3-17
Tasks in Handling Threads .................................................................................................................. 3-18
Review of Servlet Life Cycle ................................................................................................................ 3-22
Exercise: Modifying the Form-Processing Servlet ........................................................................... 3-24
Check Your Progress ............................................................................................................................ 3-25
Think Beyond ........................................................................................................................................ 3-27

Beyond CGI: Developing Java Servlets xxxiii


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

Database Access .....................................................................................................................4-1


Overview .................................................................................................................................................. 4-2
Distributed Models ................................................................................................................................. 4-3
Distributed Java Technologies .............................................................................................................. 4-4
Java Database Connectivity (JDBC) ...................................................................................................... 4-5
An Example Database Servlet ............................................................................................................... 4-6
Loading the Database Driver ................................................................................................................ 4-8
Establishing a Connection to the Database ......................................................................................... 4-9
Creating and Executing a Query ........................................................................................................ 4-10
Parsing and Displaying the Results ................................................................................................... 4-11
Closing the Connection ........................................................................................................................ 4-12
JDBC and Servlets ................................................................................................................................. 4-13
Connection Pools ................................................................................................................................... 4-14
Items to Consider .................................................................................................................................. 4-15
Implementing a Connection Pool ....................................................................................................... 4-16
A Connection Pool Client .................................................................................................................... 4-17
An Example Connection Pool Client Servlet .................................................................................... 4-18
The ConnectionPool API ................................................................................................................... 4-19
The ConnectionPool Constructor ..................................................................................................... 4-20
The addConnection Method .............................................................................................................. 4-21
The getNewConnection Method ........................................................................................................ 4-22
The getConnection Method .............................................................................................................. 4-23
The releaseConnection Method ..................................................................................................... 4-25
The closeAll Method ......................................................................................................................... 4-27
Review of Database Access .................................................................................................................. 4-28
Exercise: Enhancing a Database Servlet ............................................................................................. 4-30
Check Your Progress ............................................................................................................................ 4-31
Think Beyond ........................................................................................................................................ 4-33

Beyond CGI: Developing Java Servlets xxxiv


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

RMI and CORBA/IDL ...........................................................................................................5-1


Overview .................................................................................................................................................. 5-2
Java RMI ................................................................................................................................................... 5-3
Interaction Between RMI Client, Server, and Registry ...................................................................... 5-4
Implementing a Basic RMI Server ........................................................................................................ 5-5
Implementing a Basic RMI Client ......................................................................................................... 5-6
Installing and Invoking the Server, Client, and RMI Registry ......................................................... 5-7
RMI and Servlets ..................................................................................................................................... 5-8
An Example RMI Servlet Solution ........................................................................................................ 5-9
An Example RMI Server ...................................................................................................................... 5-10
An Example RMI Client ....................................................................................................................... 5-16
Java IDL .................................................................................................................................................. 5-22
Review of RMI and CORBA/IDL ....................................................................................................... 5-23
Exercise: Configuring and Invoking the RMI Example .................................................................. 5-24
Check Your Progress ............................................................................................................................ 5-25
Think Beyond ........................................................................................................................................ 5-26

Persistent State in HTTP Servlets .......................................................................................6-1


Overview .................................................................................................................................................. 6-2
Benefits and Limitations of Statelessness in the HTTP Protocol ...................................................... 6-3
Demonstrating the Benefits of State ..................................................................................................... 6-4
Cookies ..................................................................................................................................................... 6-5
Programming With Cookies .................................................................................................................. 6-6
Setting a Cookie ....................................................................................................................................... 6-7
Retrieving a Cookie ................................................................................................................................ 6-8
Sessions ..................................................................................................................................................... 6-9
The HttpSession Interface ................................................................................................................. 6-10
Example .................................................................................................................................................. 6-11
The Login Servlet .................................................................................................................................. 6-12
The Login Servlet: init Method ........................................................................................................ 6-13

Beyond CGI: Developing Java Servlets xxxv


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

The Login Servlet: doPost Method .................................................................................................... 6-14


The Secret Servlet .................................................................................................................................. 6-16
The Secret Servlet: doGet Method ...................................................................................................... 6-17
Additional Guidelines .......................................................................................................................... 6-18
Tying a Session to a Browser ............................................................................................................... 6-19
Cookies and Sessions Compared ........................................................................................................ 6-20
Review of Cookies and Sessions ......................................................................................................... 6-21
Exercise: Developing a Web Shopping Solution .............................................................................. 6-23
Check Your Progress ............................................................................................................................ 6-24
Think Beyond ........................................................................................................................................ 6-25

Time-Extended Connections .................................................................................................7-1


Overview .................................................................................................................................................. 7-2
What Is a Time-Extended Connection? ............................................................................................... 7-3
Implementation Options ........................................................................................................................ 7-4
HTML and Dynamic Updates ............................................................................................................... 7-5
Java Technology and Dynamic Updates ............................................................................................. 7-6
Continuous or Transient TCP Connections ........................................................................................ 7-7
User Datagram Protocol ......................................................................................................................... 7-8
Broadcast and Multicast Connections .................................................................................................. 7-9
Review of Time-Extended Connections ............................................................................................ 7-10
Exercise: Developing a UDP Broadcast Transaction Monitor ........................................................ 7-11
Check Your Progress ............................................................................................................................ 7-12
Think Beyond ........................................................................................................................................ 7-13

Servlet Security .......................................................................................................................8-1


Overview .................................................................................................................................................. 8-2
Major Threats to Web Server Security ................................................................................................. 8-3
Authentication and Authorization ....................................................................................................... 8-4
Types of HTTP Authentication ............................................................................................................. 8-5

Beyond CGI: Developing Java Servlets xxxvi


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

Security Realms ....................................................................................................................................... 8-6


Basic HTTP Authentication In-Depth .................................................................................................. 8-7
Implementing Basic Authentication in a Servlet ................................................................................ 8-9
An Example Basic Authentication Servlet ......................................................................................... 8-10
Examples of Server-Independent Validation .................................................................................... 8-12
Additional Security Features of Java Web Server ............................................................................ 8-13
Secure Administration With SSL ........................................................................................................ 8-14
Servlet Sandbox ..................................................................................................................................... 8-15
Servlet Types .......................................................................................................................................... 8-16
RemoteUser Property ........................................................................................................................... 8-17
Sanity Checking ..................................................................................................................................... 8-18
Review of Servlet Security ................................................................................................................... 8-19
Exercise: Basic and Certificate Authentication Servlets .................................................................. 8-20
Check Your Progress ............................................................................................................................ 8-21
Think Beyond ........................................................................................................................................ 8-22

Servlet Beans ...........................................................................................................................9-1


Overview .................................................................................................................................................. 9-2
What Is JavaBeans? ................................................................................................................................. 9-3
Functionality of Beans ............................................................................................................................ 9-4
What Is a Servlet Bean? .......................................................................................................................... 9-5
An Example Servlet Bean ....................................................................................................................... 9-6
Setting Header Information ................................................................................................................... 9-8
get and set Accessor and Mutator Methods ........................................................................................ 9-9
Servlet Beans Persistence ..................................................................................................................... 9-10
An Example of Writing to a Serialization File .................................................................................. 9-11
Packaging Servlet Beans ....................................................................................................................... 9-12
Servlet Bean Instantiation .................................................................................................................... 9-13
Invoking Servlet Beans ......................................................................................................................... 9-14
An Example of Invoking a Servlet Bean Using a URL .................................................................... 9-15

Beyond CGI: Developing Java Servlets xxxvii


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

Review of Servlet Beans ....................................................................................................................... 9-18


Exercise: Creating a Servlet Bean ........................................................................................................ 9-19
Check Your Progress ............................................................................................................................ 9-20
Think Beyond ........................................................................................................................................ 9-21

Dynamic Web Content .........................................................................................................10-1


Overview ................................................................................................................................................ 10-2
Generating Dynamic Content ............................................................................................................. 10-3
CGI print Statements .......................................................................................................................... 10-4
Servlet println Statements ................................................................................................................ 10-5
Servlet println and Perl print Statements ..................................................................................... 10-6
JavaServer Pages ................................................................................................................................... 10-7
An Example Java Server Page ............................................................................................................. 10-8
JavaServer Pages Syntax ...................................................................................................................... 10-9
Directives .............................................................................................................................................. 10-10
Declarations ......................................................................................................................................... 10-11
Scriptlets ............................................................................................................................................... 10-12
Expressions .......................................................................................................................................... 10-13
Additional Guidelines ........................................................................................................................ 10-14
The <BEAN> Tag ................................................................................................................................... 10-15
An Example JavaServer Page Using the <BEAN> Tag .................................................................... 10-16
Declaring a Bean .................................................................................................................................. 10-18
PageCompileServlet ............................................................................................................................ 10-20
An Example JavaServer Page ............................................................................................................ 10-22
An Example Servlet Created From a JavaServer Page .................................................................. 10-23
Creating a Servlet from a JavaServer Page ...................................................................................... 10-25
Review of JavaServer Pages ............................................................................................................... 10-26
Exercise: Creating JavaServer Pages ................................................................................................ 10-28
Check Your Progress .......................................................................................................................... 10-29
Think Beyond ...................................................................................................................................... 10-30

Beyond CGI: Developing Java Servlets xxxviii


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

You might also like