SL310 - Beyond CGI Developing Java Servlets - Oh - 0898
SL310 - Beyond CGI Developing Java Servlets - Oh - 0898
SL-310
Preface
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
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 August 1998, Revision A
Sun Educational Services
Course Map
Introduction to Servlets
Forms Processing
Servlet Basics
With Servlets
Distributed Servlets
Collaborative Servlets
Servlet Security
Servlet
Security
Servlet Hybrids
Module-by-Module Overview
• Module 1 – Servlet Basics
• Module 2 – Forms Processing With Servlets
• Module 3 – Servlet Lifecycle
• Module 4 – Database Access
• Module 5 – RMI and CORBA/IDL
• Module 6 – Persistent State in HTTP Servlets
Module-by-Module Overview
• Module 7 – Time Extended Connections
• Module 8 – Servlet Security
• Module 9 – Servlet Beans
• Module 10 – Dynamic Web Content
Course Objectives
• Develop a simple hypertext transfer protocol (HTTP)
servlet.
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.
Skills Gained 1 2 3 4 5 6 7 8 9 10
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
Icons
• Demonstration
• Reference
• Discussion
• Exercise
Typographical Conventions
• Courier – Commands, files, and directories, on-screen
computer output
Module 1
Servlet Basics
Overview
• Course map
• Relevance
• Objectives
Gateway
programs 2
2 Shell 3
1
HTTP request Run
CGI
CGI script
5
HTTP response Output 4
Browser
(WWW client)
HTTP (Web)
server
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.
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
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
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.
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
Think Beyond
This module primarily discussed handling servlet responses.
What might you do as part of handling a request to a servlet?
Module 2
Overview
• Course map
• Relevance
• Objectives
METHOD
• Identifies how data will be sent from browser to Web
server:
• GET
• HEAD
• POST
• PUT
• DELETE
• TRACE
• OPTIONS
Returning a Response
foreach $pair (@pairs) {
...
• Using servlets:
<FORM METHOD="POST" ACTION="http://fuggles:8080/
servlet/SimpleFormServlet">
• getQueryString
• parseQueryString
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.
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?
Module 3
Servlet Lifecycle
Overview
• Course map
• Relevance
• Objectives
Servlet Lifecycle
• 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
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
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.
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 }
• Access methods
Think Beyond
Can you think of additional, solution-specific, uses for the
three lifecycle methods: init, service, and destroy?
Module 4
Database Access
Overview
• Course map
• Relevance
• Objectives
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.
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
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
Think Beyond
What are some additional database-related modifications that
might be added to a connection pool?
Module 5
Overview
• Course map
• Relevance
• Objectives
Java RMI
• Allows access to remote objects on other JVMs
• RMI solution has three parts:
• Server
• Client
• RMI registry
1
RMI registry RMI Server JVM
**Stub
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
• Server
• Client
• RMI registry
• Exercise summary
Think Beyond
Are there any additional distributed technologies that can be
used with servlets?
Module 6
Overview
• Course map
• Relevance
• Objectives
Cookies
• Cookies are a mechanism for storing a variable and its
associated value on the browser.
Setting a Cookie
1. Create the cookie:
Cookie c = new Cookie("MyName", "MyValue");
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 }
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.
Example
• Two servlets:
• Login servlet
• Secret servlet
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.
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?
Module 7
Time-Extended Connections
Overview
• Course map
• Relevance
• Objectives
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
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
• Exercise summary
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?
Module 8
Servlet Security
Overview
• Course map
• Relevance
• Objectives
Security Realms
• Contain users, groups, and their ACLs
• Realms in Java Web Server
• UNIXRealm
• NTRealm
• defaultRealm
• CertificateRealm
• servletMgrRealm
• SharedPasswordRealm
Yes
No
No
Encode
Send 401
user:pass
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
Servlet Sandbox
• Remote servlets are untrusted.
Servlet Types
• Trusted servlets
• Java Web Server-internal servlets
• Local servlets
• Signed network servlets
• Unsigned network servlets
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
Sanity Checking
• You will know the parameters a servlet will receive.
• Check all request parameters that access volatile data
for validity.
Think Beyond
How might security be implemented in the exercises used
throughout this course?
Module 9
Servlet Beans
Overview
• Course map
• Relevance
• Objectives
What Is JavaBeans?
• Portable, platform-independent component model
• Written in the Java programming language
• Beans
• Reusable software pieces
• Combined to create application or applet
Functionality of Beans
• Introspectable
• Event aware
• Customizable
• Persistent
• ObjectOutputStream and
ObjectOutput classes
• writeObject method
Counter.class
counter1.ser
• http://host_name:port/servlet/hello2
• http://host_name:port/servlet/Hello
Think Beyond
How might you use the JavaBeans event mechanism to extend
the functionality of your servlet Beans?
Module 10
Overview
• Course map
• Relevance
• Objectives
</HEAD><BODY><h1>Hello World</h1></BODY></HTML>";
JavaServer Pages
• Web pages containing a combination of HTML and
code
• Benefits of using JSP
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" %>
Declarations
• SCRIPT tags
<SCRIPT runat=server>
</SCRIPT>
int i = 0;
// some code;
Scriptlets
• A portion of scripting code providing additional
functionality to HTML
Expressions
• Are variables substituted with values after the value is
resolved.
• Are defined within <%= and %>
• Example JavaServer page expression:
<% int number = 20;
<p>
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.
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
Declaring a Bean
• create
• scope
• request
• session
• beanName
PageCompileServlet
• Invoked when client requests a JavaServer page
• Loaded and initialized as any other servlet
• Compiles JSP files into servlets
PageCompileServlet
Think Beyond
How might you use JavaServer Pages on your Web site?