JavaServlets PDF
JavaServlets PDF
Training Index
Preface
By MageLang Institute
The JavaSM Developer ConnectionSM (JDC) presents a Short Course
on the Fundamentals of Java Servlets written by Java Software
licensee, the MageLang Institute. A leading provider of JavaTM
technology training, MageLang has contributed regularly to the JDC
since 1996.
The MageLang Institute, since its founding in 1995, has been
dedicated to promoting the growth of the Java technology
community by providing excellent education and acting as an
independent resource. To find out more about MageLang's Java
technology training, visit the MageLang web site.
Reader Feedback
Tell us what you think of this tutorial.
reading
If you have other comments or ideas for future articles,
please type them here:
Submit Reset
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
Introduction
By MageLang Institute
Course Notes
Magercises
Back to Preface and Reader Feedback
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
Training Index
Course Notes
MageLang Institute
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
HTTP
URL,
FTP,
URL,
or a custom protocol.
The request and the corresponding response reflect the state of the
client and the server at the time of the request. Normally, the state
of the client/server connection cannot be maintained across
different request/response pairs. However, session information is
maintainable with servlets through means to be described later.
The Java Servlet API includes several Java interfaces and fully
defines the link between a hosting server and servlets. The Servlet
API is defined as an extension to the standard JDK. JDK extensions
are packaged under javax--the root of the Java extension library
tree. The Java Servlet API contains the following packages:
Package javax.servlet
Package javax.servlet.http
Servlets are a powerful addition to the Java environment. They are
fast, safe, reliable, and 100% pure Java. Because servlets plug into
an existing server, they leverage a lot of existing code and
Middle-Tier Process
Transaction management
Proxy Servers
Protocol Support
The Servlet API provides a tight link between a server and servlets.
This allows servlets to add new protocol support to a server. (You
will see how HTTP support is provided for you in the API packages.)
Essentially, any protocol that follows a request/response computing
POP
FTP
HTML Support
HTML can provide a rich presentation of information because of its
flexibility and the range of content that it can support. Servlets can
play a role in creating HTML content. In fact, servlet support for
HTML is so common, the javax.servlet.http package is dedicated to
supporting HTTP protocol and HTML generation.
Complex web sites often need to provide HTML pages that are
tailored for each visitor, or even for each hit. Servlets can be
written to process HTML pages and customize them as they are sent
to a client. This can be as simple as on the fly substitutions or it can
be as complex as compiling a grammar-based description of a page
and generating custom HTML.
Some web servers, such as the Java Web ServerTM (JWS), allow
servlet tags to be embedded directly into HTML files. When the
server encounters such a tag, it calls the servlet while it is sending
the HTML file to the client. This allows a servlet to insert its
contribution directly into the outgoing HTML stream.
Server-Side Includes
Installing Servlets
Servlets are not run in the same sense as applets and applications.
Servlets provide functionality that extends a server. In order to test
a servlet, two steps are required:
1. Install the servlet in a hosting server
2. Request a servlet's service via a client request
There are many web servers that support servlets. It is beyond the
scope of this course to cover the different ways to install servlets in
each server. This course examines the JSDK's servletrunner utility and
the JWS.
Servlets can be started and stopped for each client request, or they
can be started as the web server is started and kept alive until the
server is shut down. Temporary servlets are loaded on demand and
offer a good way to conserve resources in the server for less-used
functions.
Permanent servlets are loaded when the server is started, and live
until the server is shutdown. Servlets are installed as permanent
extensions to a server when their start-up costs are very high (such
as establishing a connection with a DBMS), when they offer
permanent server-side functionality (such as an RMI service), or
when they must respond as fast as possible to client requests.
There is no special code necessary to make a servlet temporary or
permanent; this is a function of the server configuration.
Because servlets can be loaded when a web server starts, they can
use this auto-loading mechanism to provide easier loading of
server-side Java programs. These programs can then provide
functionality that is totally unique and independent of the web
server. For example, a servlet could provide R-based services
(rlogin, rsh, ...) through TCP/IP ports while using the servlet
request/response protocol to present and process HTML pages used
to manage the servlet.
Using servletrunner
For both JDK 1.1 and the Java 2 platform, you need to install the
Java Servlet Development Kit (JSDK). To use servletrunner, make
sure your PATH environment variable points to its directory. For the
JSDK 2.0 installed with all default options, that location is:
c:\jsdk2.0\bin on a Windows platform.
Magercise
Sun's Java Web Server (JWS) is a full featured product. For servlet
developers, a nice feature is its ability to detect when a servlet has
been updated. It detects when new class files have been copied to
the appropriate servlet directory and, if necessary, automatically
reloads any running servlets.
The JWS can be installed as a service under Windows NT. While this
makes it convenient for running a production server, it is not
recommended for servlet development work. Under Windows 95,
there are no OS services, so the command line start-up is your only
option.
To run JWS from the c:\JavaWebServer1.1\bin directory, type in the
httpd command. This starts the server in a console window. No
further display is shown in the console unless a servlet executes a
System.out.println() statement.
when servlets have been added to this directory. Although you can
use the JWS management applet to tailor the servlet installation,
this is generally not advised except for production server
installations.
To shut down the JWS, press <Control>+C in the command
window. The server prints a message to the console when it has
finished shutting down.
Magercise
Servlet API
The Java Servlet API defines the interface between servlets and
servers. This API is packaged as a standard extension to the JDK
under javax:
Package javax.servlet
Package javax.servlet.http
The API provides support in four categories:
Servlet life cycle management
Servlets run on the web server platform as part of the same process
as the web server itself. The web server is responsible for
initializing, invoking, and destroying each servlet instance.
A web server communicates with a servlet through a simple
interface, javax.servlet.Servlet. This interface consists of three main
methods:
init()
service()
destroy()
and two ancillary methods:
getServletConfig()
getServletInfo()
You may notice a similarity between this interface and that of Java
applets. This is by design! Servlets are to web servers what applets
are to web browsers.An applet runs in a web browser, performing
actions it requests through a specific interface. A servlet does the
same, running in the web server.
Sample Servlet
import java.io.*;
import javax.servlet.*;
public SampleServlet implements Servlet {
private ServletConfig config;
}
}
Servlet Context
A servlet lives and dies within the bounds of the server process. To
understand its operating environment, a servlet can get information
about its environment at different times. Servlet initialization
information is available during servlet start-up; information about
the hosting server is available at any time; and each service
request can contain specific contextual information.
servlet.dateprinter.code=DatePrinterServlet
servlet.dateprinter.timezone=PST
or this information could be supplied through a GUI administration
tool.
The timezone information would be accessed by the servlet with the
following code:
String timezone;
public void init(ServletConfig config) {
timeZone = config.getInitParameter("timezone");
}
An Enumeration of all initialization parameters is available to the
servlet via the getInitParameterNames() method.
The following example code shows how a servlet uses the host
server to write a message to a servlet log when it initializes:
BufferedReader reader;
String param1;
String param2;
public void service (
ServletRequest req,
ServletResponse res) {
reader = req.getReader();
param1 = req.getParameter("First");
param2 = req.getParameter("Second");
}
There are additional pieces of information available to the servlet
through ServletRequest. These are shown in the following table.
Magercise
Utility Classes
There are several utilities provided in the Servlet API. The first is
the interface javax.servlet.SingleThreadModel that can make it easier to
write simple servlets. If a servlet implements this marker interface,
the hosting server knows that it should never call the servlet's
service() method while it is processing a request. That is, the server
processes all service requests within a single thread.
While this makes it easier to write a servlet, this can impede
performance. A full discussion of this issue is located later in this
course.
Two exception classes are included in the Servlet API. The
exception javax.servlet.ServletException can be used when there is a
general failure in the servlet. This notifies the hosting server that
there is a problem.
The exception javax.servlet.UnavailableException indicates that a servlet
is unavailable. Servlets can report this exception at any time. There
are two types of unavailability:
HTTP Support
Servlets that use the HTTP protocol are very common. It should not
be a surprise that there is specific help for servlet developers who
write them. Support for handling the HTTP protocol is provided in
the package javax.servlet.http. Before looking at this package, take a
look at the HTTP protocol itself.
HTTP stands for the HyperText Transfer Protocol. It defines a
protocol used by web browsers and servers to communicate with
each other. The protocol defines a set of text-based request
messages called HTTP methods. (Note: The HTTP specification calls
these HTTP methods; do not confuse this term with Java methods.
Think of HTTP methods as messages requesting a certain type of
response). The HTTP methods include:
GET
HEAD
POST
PUT
DELETE
TRACE
CONNECT
OPTIONS
For this course, you will only need to look at only three of these
methods: GET, HEAD, and POST.
The HTTP GET method requests information from a web server. This
information could be a file, output from a device on the server, or
output from a program (such as a servlet or CGI script).
An HTTP GET request takes the form:
GET URL <http version>
Host: <target host>
in addition to several other lines of information.
For example, the following HTTP GET message is requesting the
home page from the MageLang web site:
GET / HTTP/1.1
Connection: Keep-Alive
User-Agent: Mozilla/4.0 (
compatible;
MSIE 4.01;
Windows NT)
Host: www.magelang.com
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg
On most web servers, servlets are accessed via URLs that start with
/servlet/. The following HTTP GET method is requesting the servlet
MyServlet on the host www.magelang.com:
GET /servlet/MyServlet?name=Scott&
company=MageLang%20Institute HTTP/1.1
Connection: Keep-Alive
User-Agent: Mozilla/4.0 (
compatible;
MSIE 4.01;
Windows NT)
Host: www.magelang.com
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg
The URL in this GET request invokes the servlet called MyServlet and
contains two parameters, name and company. Each parameter is a
name/value pair following the format name=value. The parameters
are specified by following the servlet name with a question mark
('?'), with each parameter separated by an ampersand ('&').
Note the use of %20 in the company's value. A space would signal
the end of the URL in the GET request line, so it must be "URL
encoded", or replaced with %20 instead. As you will see later,
servlet developers do not need to worry about this encoding as it
will be automatically decoded by the HttpServletRequest class.
HTTP GET requests have an important limitation. Most web servers
limit how much data can be passed as part of the URL name
(usually a few hundred bytes.) If more data must be passed
between the client and the server, the HTTP POST method should be
used instead.
It is important to note that the server's handling of a GET method is
expected to be safe and idempotent. This means that a GET method
will not cause any side effects and that it can be executed
repeatedly.
When a server replies to an HTTP GET request, it sends an HTTP
response message back. The header of an HTTP response looks like
the following:
The HTTP HEAD method is very similar to the HTTP GET method. The
request looks exactly the same as the GET request (except the word
HEAD is used instead of GET), but the server only returns the header
information.
HEAD is often used to check the following:
The last-modified date of a document on the server for caching
purposes
The size of a document before downloading (so the browser
can present progress information)
The server type, allowing the client to customize requests for
that server
The type of the requested document, so the client can be sure
it supports it
Note that HEAD, like GET, is expected to be safe and idempotent.
Pay special attention to the third bullet above. The HTTP GET
request passes all its arguments as part of the URL. Many web
servers have a limit to how much data they can accept as part of
the URL. The POST method passes all of its parameter data in an
input stream, removing this limit.
A typical POST request might be as follows:
name=Scott&company=MageLang%20Institute
Note the blank line--this signals the end of the POST request header
and the beginning of the extended information.
Unlike the GET method, POST is not expected to be safe nor
idempotent; it can perform modifications to data, and it is not
required to be repeatable.
Now that you have been introduced to the HTTP protocol, consider
how the javax.servlet.http package helps you write HTTP servlets. The
abstract class javax.servlet.http.HttpServlet provides an implementation
of the javax.servlet.Servlet interface and includes a lot of helpful
default functionality. The easiest way to write an HTTP servlet is to
extend HttpServlet and add your own custom processing.
The class HttpServlet provides an implementation of the service()
method that dispatches the HTTP messages to one of several
special methods. These methods are:
doGet()
doHead()
doDelete()
doOptions()
doPost()
doTrace()
When using the HTTP support classes, you generally create a new
servlet that extends HttpServlet and overrides either doGet() or
doPost(), or possibly both. Other methods can be overridden to get
more fine-grained control.
The HTTP processing methods are passed two parameters, an
HttpServletRequest object and an HttpServletResponse object. The
HttpServletRequest class has several convenience methods to help
parse the request, or you can parse it yourself by simply reading
the text of the request.
A servlet's doGet() method should
Read request data, such as input parameters
Set response headers (length, type, and encoding)
Write the response data
It is important to note that the handling of a GET method is
expected to be safe and idempotent.
Handing is considered safe if it does not have any side effects
for which users are held responsible, such as charging them
for the access or storing data.
Handling is considered idempotent if it can safely be repeated.
This allows a client to repeat a GET request without penalty.
Think of it this way: GET should be "looking without touching." If
you require processing that has side effects, you should use another
HTTP method, such as POST.
A servlet's doPost() method should be overridden when you need to
process an HTML form posting or to handle a large amount of data
being sent by a client. HTTP POST method handling is discussed in
detail later.
HEAD requests are processed by using the doGet() method of an
HttpServlet. You could simply implement doGet() and be done with it;
any document data that you write to the response output stream
will not be returned to the client. A more efficient implementation,
however, would check to see if the request was a GET or HEAD
request, and if a HEAD request, not write the data to the response
output stream.
Summary
The Java Servlet API is a standard extension. This means that there
Servlet Examples
Now for an in-depth look at several servlets. These examples
include:
Generating Inline Content
<servlet code="DatePrintServlet">
<param name=timezone value=pst>
</servlet>
This tag causes the invoking of a servlet named DatePrintServlet to
generate some in-line content.
Magercise
Magercise
Using Cookies
int sum = 0;
Cookie theCookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
theCookie = cookies[i];
if (theCookie.getName().equals(SUM_KEY)) {
try {
sum = Integer.parseInt(theCookie.getValue());
} catch (NumberFormatException ignored) {
sum = 0;
}
break;
}
}
}
The complete code example shown above is available for testing.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" +
"<head><title>Session Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Session Information</h1><table>");
out.println ("<tr><td>Identifier</td>");
out.println ("<td>" + session.getId() + "</td></tr>");
out.println ("<tr><td>Created</td>");
out.println ("<td>" + new Date(
session.getCreationTime()) + "</td></tr>");
out.println ("<tr><td>Last Accessed</td>");
out.println ("<td>" + new Date(
session.getLastAccessedTime()) + "</td></tr>");
out.println ("<tr><td>New Session?</td>");
out.println ("<td>" + session.isNew() + "</td></tr>");
String names[] = session.getValueNames();
for (int i=0, n=names.length; i<n; i++) {
out.println ("<tr><td>" + names[i] + "</td>");
out.println ("<td>" + session.getValue (names[i])
+ "</td></tr>");
}
out.println("</table></center></body></html>");
out.close();
The complete code example shown above is available for testing.
One thing not demonstrated in the example is the ability to end a
session, where the next call to request.getSession(true) returns a
different session. This is done with a call to invalidate().
In the event a user has browser cookies disabled, you can encode
the session ID within the HttpServletResponse by calling its encodeUrl()
method.
Connecting to Databases
try {
// Submit query
stmt = con.createStatement();
result = stmt.executeQuery (
"SELECT programmer, cups " +
"FROM JoltData ORDER BY cups DESC;");
// Create output
PrintWriter out = response.getWriter();
while(result.next()) {
// Generate output from ResultSet
}
} finally {
if (result != null) {
result.close();
}
if (stmt != null) {
stmt.close();
}
}
out.flush();
out.close();
}
In the destroy() method disconnect from the database.
public void destroy() {
super.destroy();
con.close();
}
It is not good practice to leave a database connection permanently
open, so this servlet should not be installed as a permanent servlet.
Having it as a temporary servlet that closes itself down after a
predefined period of inactivity allows the sharing of the database
connection with requests that coincide, reducing the cost of each
request.
You can also save some information in the HttpSession to possible
page through the result set.
Security Issues
As with Java applets, Java servlets have security issues to worry
about, too.
Many web servers allow you to restrict access to certain web pages
and servlets via access control lists (ACLs). An ACL is a list of users
who are allowed to perform a specific function in the server. The list
specifies:
What kind of access is allowed
Each web server has its own means of specifying an ACL, but in
general, a list of users is registered on the server, and those user
names are used in an ACL. Some servers also allow you to add
users to logical groups, so you can grant access to a group of users
without specifying all of them explicitly in the ACL.
ACLs are extremely important, as some servlets can present or
modify sensitive data and should be tightly controlled, while others
only present public knowledge and do not need to be controlled.
Threading Issues
A web server can call a servlet's service() method for several
requests at once. This brings up the issue of thread safety in
servlets.
But first consider what you do not need to worry about: a servlet's
init() method. The init() method will only be called once for the
duration of the time that a servlet is loaded. The web server calls
init() when loading, and will not call it again unless the servlet has
been unloaded and reloaded. In addition, the service() method or
destroy() method will not be called until the init() method has
completed its processing.
Things get more interesting when you consider the service() method.
The service() method can be called by the web server for multiple
clients at the same time. (With the JSDK 2.0, you can tag a servlet
with the SingleThreadModel interface. This results in each call to
service() being handled serially. Shared resources, such as files and
databases, can still have concurrency issues to handle.)
If your service() method uses outside resources, such as instance
data from the servlet object, files, or databases, you need to
carefully examine what might happen if multiple calls are made to
service() at the same time. For example, suppose you had defined a
counter in your servlet class that keeps track of how many service()
counter = counter - 1;
What would happen if two service() methods were running at the
same time, and both executed line 1 before either executed line 2?
Both would have the same value for myNumber, and the counter
would not be properly updated.
For this situation, the answer might be to synchronize the access to
the counter variable:
synchronized(this) {
myNumber = counter + 1;
counter = myNumber;
}
synchronized(this) {
counter = counter - 1 ;
}
This ensures that the counter access code is executed only one
thread at a time.
There are several issues that can arise with multi-threaded
execution, such as deadlocks and coordinated interactions. There
are several good sources of information on threads, including Doug
Lea's book Concurrent Programming in Java.
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.
Training Index
Magercises
By MageLang Institute
Magercises
1. Hosting with servletrunner
This Magercise shows you how to build a simple servlet and
host it with the servletrunner utility.
Educational goals:
Compile a simple "Hello World" servlet.
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's Copyright 1995-99 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Legal Terms. Privacy Policy.