Home

Architecture

Servlets and JSP

Database

Administration

Web Search

News

Java Servers

Web Services

Enterprise

Learning

Contact Us

Learning: Java - EJB - Jumppoint -Servlets- JSP - JMS - JNDI- JDBC - RMI

Learn: Servlets


Learning Servlets: Web programs with many purposes.. Updated Nov 19, 2001
Tutorials
Examples
Building Servlets:
HTTP

Get & Post
Authoring

Applets to
to Servlet
to Databases
to EJBs

DHTML
Filtering
Redirects
Sessions

Deploying WebApps
(in Tomcat)

Patterns for WebApps: MVC

Best Practices

Books
Servlet API Packages: javax.servlet
javax.servlet.http
   
See also:
Java Skyline:
Learn JSP
Java Skyline:
Servlets and JSP
Java Skyline: Servlet Engines
jGuru: Servlet FAQ, Tomcat FAQ

A Servlet is an application program you write that runs on a web server. The servlet accepts and processes web requests through CGI (Common Gateway Interface) get or post requests. See Servlets and JSP: What are Servlets?, Internet.com. Servlets are also the basis upon which JSP is implemented.

How it works: A Servlet is actually a Java class you write that extends the javax.servlet.HttpServlet class. Here's how your servlet works:

  • A Web server receives an HTTP GET or POST request from a browser (or other TCP client)
  • The web server directs the HTTP request to the servlet engine (in the same way that direct CGI requests).
  • If your servlet is not already in memory, the servlet engine loads it and initializes it.
  • The servlet engine then encapsulates the HTTP request into a class called HttpServletRequest and delivers it to your servlet's doPost or doGet method.
  • Your servlet responds by writing HTML into HttpServletResponse which is sent back to the web server and delivered back to the TCP client.

For an excellent overview of servlet engine architecture see Java Servlets: Design Issues by Dr. Subrahmanyam A.V.B.

Servlets can do many tasks. They can be simple applications, or they can operate as front-ends for complex J2EE systems.

Getting Started: To begin using servlets, you need to download Tomcat or Java Servlet Development Kit (JSDK or JWSDK) from Sun or any other servlet engine. All of them are easy to install on Windows, Mac, and Unix. They all enable your computer to run as servlet-enabled web server. The original JSDK (circa 1996-2000) itself was actually a small servlet engine. Tomcat and other servlet engines generally provide more advanced features than the JSDK. Recent servlet engines also incorporate JavaServer Pages (JSP).

Installation of Tomcat. See JavaSkyline: Learn JSP: Getting Started for a instructions on Tomcat installation.

Some servlet engines provide a full-featured web server and possibly many other capabilities. Others operate as a add-on for other web servers such as Apache, Microsoft IIS, iPlanet, or WebSphere. And some have more recent implementations of the Servlet API. But with this exception, the API is just about identical from engine to engine.

Tutorials

Highly Recommended: The Servlet/JSP tutorial series by Marty Hall provides quick start information that will get you going. Also take a look at the classic and highly comprehenive tutorials in Servlet Essentials by Stefan Zeiger of Novocode and finally, an excellent series by Dick Baldwin Advanced Java Programming Tutorial which discusses servlets and other topics as well.

Introductory. Paul Philion provides an informative introductory overview and tutorial Build servlet-based enterprise Web applications on creating efficient servlets from JavaWorld, Dec 1998. New: A more recent introductory tutorial is Care and feeding of Java servlets by Rick Scott on CNet's Builder Site, Oct 2001. In particular, it provides a comparison of Servlets and CGI scripts - something someone should have done long ago.

Sun provides a basic tutorial,
Basic Java Lesson 5: Writing Servlets by Monica Pawlan. Sun Java Developer's Connection offers Fundamentals of Java Servlet Programming a MageLang short course on learning servlets...and hey...maybe you didn't notice but..servlets went mainstream back in early 1999 when HotWired provided a quick and easy learning tutorial: Java Servlets by Dr. Richard Blaylock, Feb 11, 1999.

Advanced: Within a robust design, servlets are only a portion of a fully-functional on-line application. The complete application may provide many other objects and services. In fact, in some views, a servlet should do "as little as possible."

Servlets are essentially "stateless." They must interact with other objects (such as sessions) to be able to track a user through a series of actions. On Servlet Central, Clint Daulton offers
some philosophy on how to write servlets - a kind of Zen and the Art of Servlets.

Examples

See the Java Skyline: WebApps page. It provides a large list of servlet examples and example libraries. When you download Tomcat or another servlet engine they generally come also come with a small set of examples.

Building a Servlet Application

HTTP: The servlet is the web front-end of what may be, or may eventually become a larger application. The servlets primary responsibility is handling communications with an HTTP/TCP client.

HTTP clients in general: When you think of TCP clients, you generally think of a Web browser. However, you can communicate with a servlet from any TCP client. This means you can write a desktop Java application or Applet (see below), a Unix Telnet app or a Windows WinInet application - anything that can issue an HTTP POST request (or GET request).

POST requests are generally more robust. One simple way to send a POST request is to submit an HTML FORM in a Web browser with METHOD=POST. The form would look like this:

<FORM ACTION=http://mydomain:80/servlet/MyServlet METHOD=POST>
<INPUT TYPE = "SUBMIT" NAME= "Post">
</FORM>

It's a good idea to set up a servlet so that it can respond to both GET and POST. You can do this very easily by just having your doGet() method call doPost() like this:

doGet (HttpServlet Request req, HttpServletResponse resp)
throws ServletException, IOException {

doPost(req, resp);

}

HTTP GET and POST requests: If your servlet does not seem to be receiving TCP parameters and requests properly, you can have the TCP client send the request to SnoopServlet. SnoopServlet displays the values of all parameters sent in your GET or POST request.

To see what your own TCP requests send, cut-and-paste the above link into your browser and edit it to try your own GET request. SnoopServlet.java is included with TomCat and the Sun JSDK, and there are also copies of SnoopSerlvet here on INRIA or here on WebLogic (or here on Towson.edu). Weblogic also has a SnoopServlet written in JSP called SnoopSevlet.html, BEA Systems, WebLogic Docs. For a detailed discussion and examples of Servlet doGet() and doPost() see Servlets: A Technical Discussion, Anatomy of a Servlet Part 1, Part 2, and Part 3 on Servlet.Inc.

Authoring Tools

Writing Servlets with authoring tools: You do not need a full-blown GUI IDE to write a servlet. Servlets do not have GUI interfaces like applets. They have an HTTP interface. So, keep it simple. Instead of an IDE, try using a UML tool - such as one of those listed on the Architecture page. You can also use an authoring tool listed on the Servlet & JSP page and you can use JavaServer Pages. These tools may not make you a servlet expert. But they can shorten the prototyping and development time. Or use a simple text editor or Java-enabled text editor such as TextPad, JEdit, Jext, or Emacs.

Applet to Servlet

For an applet to contact a servlet it needs to know the URL of the servlet - the server DNS plus the servlet location. There are a number of articles and examples that describe applet-servlet communication in general:

Servlet to Servlet

Servlets can communicate with other servlets as well - in a number of ways including chaining, sessions, servlet contexts, and shared objects as explained by Allan Williamson's article Servlet to Servlet Communication, JDJ May 2000. And short of object sharing example appears in Question of the Week 58: Sharing Objects Between Servers, Joseph Mocker, answer provided by user fschoong (JDC) Oct 1999.

Database

Servlet to Database (JDBC) Connections: The first time you use JDBC in the servlet environment will probably be the first time you've ever had to change the classpath for the sevlet engine. The servlet engine needs to find the JDBC driver. Each servlet engine has it's own way to load the classpath.

For TomCat, all you do is copy the JDBC driver into Tomcat's lib directory and restart Tomcat. For other servlet engines, you'll have to read the instructions or the installation guide or examine the startup script for your servlet engine to find out how to set the classpath.

To ensure that you did change the classpath correctly, try running this
SysParam servlet. It lists system properties that are currently set in the JVM.

Java Skyline provides an example database Servlet: called the
AdhocSQL. A tutorial called Servlet-database-tutorial on www.java-beans.de appears quite thorough and builds a sample servlet-database application. For another servlet-JDBC application see Servlets and JDBC by Allan Williamson, JDJ, Apr 2000.

Multi-tiered Database : Chad Darby explains a 3-tiered JDBC Web architecture in Developing 3-Tiered Applications with Java Servlets , JDJ, Jan 1999.



DHTML: See Pushlets, Part 1: Send events from servlets to DHTML client browsers by Just van den Broecke, JavaWorld, Mar 2000.

Servlet to EJB

Servlet to EJB: For starters see Java Skyline: Learn EJB, and the Bank Servlet sample under Persistence PowerTier examples (Source code is here). IBM provides an example called Stock.

When to use EJBs. Y Liang has several pages that compares using Servlet-JDBC with using stored procedures and using EJBs with regard to performance, scalability, and re-use ("changability").

DHTML: See Pushlets, Part 1: Send events from servlets to DHTML client browsers by Just van den Broecke, JavaWorld, Mar 2000.

DHTML

See Pushlets, Part 1: Send events from servlets to DHTML client browsers by Just van den Broecke, JavaWorld, Mar 2000.

Redirects

Hot Tips for Server-Side Redirects by Budi Kurniawan JavaPro Mar 2002

Servlet 2.3: Filtering

Filters for Pre- and Post-Processing Kevin Jones, JavaPro Feb 2002.

Sessions
and load balancing

What are sessions? Session tracking provides you with a way to store user specific information between servlet accesses. You can use this for a number of purposes - permissions and login validation are typical. A session is essentially object container that associated with the user by the servlet engine.

Using sessions. Web Review provides this excerpt from Java Servlet Programming: The Session Tracking API by Jason Hunter and William Crawford about session management. The excerpt discusses session tracking using HTTPSessions (the Session Tracking API), Cookies, URL rewriting, (and the famous "hidden field" method). How Do I Use Servlets for State and Session Management? by David Reilly (DDJ Java Q&A May 2000) provides an excellent tutorial with examples.

See also Stefan Zeigler's
section on sessions which uses an HTTPSession with cookies, but also uses URL rewriting as an alternative if the browser has cookie support turned off. Richard Baldwin's Advanced Java Programming Tutorial also offers several approaches to sessions including URL rewriting, hidden fields, and cookies, as well as and session API.

Load balancing and "engine preference." One historical problem with sessions in a servlet engine is that they existed only within the JVM in which the servlet engine is running. This meant that once a user had been assigned to a servlet engine, they would have to keep using that engine for their session to have continuity - meaning you could not have HTTP load balancing accross servlet engines. Several articles outline how to get around this limitation including:
Take control of the servlet environment, Part 2 Thomas E. Davis, Craig Walker (JavaWorld Dec 2000)
Manage distributed sessions Kelly Davis and Robert Di Marco (JavaWorld Apr 2001)

Newer versions of servlet engines - including Tomcat 4.0 now write sessions to disk and provide ways of sharing sessions across JVMs.

Deploying WebApps
(in TomCat)

What is a WebApp? A WebApp or web application is a collection of web-tier components such as servlets, JSPs, related pages, images, configuration files, and so on. The later specifications of the Servlet API include the ability to deploy a web application. Deployment gives you a standard way to pre-package a web application and have other people deploy it on their servers. Web apps are packaged them inside a special ".jar" file called a ".war" file.

How to create a deployment .war file is described in the jGuru TomCat FAQ under How do I deploy a War file in Tomcat? by Alex Chaffee and in Deploying Web Applications to Tomcat by James Goodwill (OnJava Apr 2001)

How to deploy a .war file. Just place the .war file in the webapps directory and restart TomCat.

Or - Avoid deployment (in Tomcat). Just about everything you read about TomCat will tell you that you must deploy servlets to use them. Well, actually you don't have to. It's very easy to manually install a servlet.

To do this there are a couple tricks.
  Using the ROOT deployment

After TomCat starts initially, it deploys its own startup applications in a "ROOT" deployment. After starting, shut down Tomcat and create create a "classes" directory under webapps\ROOT\WEB-INF. On Windows this looks like:

\jakarta-tomcat-4.0-m4\webapps\ROOT\WEB-INF\classes


Then load your servlets into this directory.

  Using the LIB directory All Java archives (Jars and Zips) that you place in TomCat's lib directory are accessable to Tomcat. Thus if you place servlets in a jar in the lib directory are accessible these servlets can be accessed by their original servlet URI names.
  Advantages to deployment There advantages to deployment, however. For one thing, placing your application into a .war file makes it easy to carry around and install.

Servlet naming You can customize the way the application is used with deployment descriptors. Descriptors can improve naming for servlets. While under older JSDKs, all servlets had to have a name like http://url.com/servlet/MyServlet. Now, you can use the <servlet-mapping> <url-pattern> deployment descriptors, to map URLs to servlets. For an example see Map URLs to Servlets for friendly surfing Budi Kurniawan, JavaPro, Apr 2002.
         

Patterns for WebApps: MVC

No discussion of servlets and web applications in general would be complete without discussing patterns. A web application is essentially a user interface, so the patterns that apply to user interfaces also apply to web applications. One common over-arching pattern for user interfaces is the "model-view-controller" (MVC) pattern. MVC has been around for a long time having originated with SmallTalk. Web Applications as Java Servlets by Brad Cox (DDJ May 2001) provides a description of MVC as a servlet application. The Apache project provides not one but two implementations of MVC frameworks:
  Velocity Velocity is a template-based MVC framework.
  Struts Struts is a servlet-JSP based MVC framework. See An Introduction to Struts by Casey Kochmer (JSP Insider Apr 2001).

Best Practices

Less is better. In fact, in some views, a servlet should do "as little as possible." From Servlet Central: Writing Good Servlets: An Overview. Jan 1999 Clint Dalton gives you a kind of "Zen and the Art of Servlets.". Along the same lines, in Servlets and the Visitor pattern on Digital Cats Sep 99, Benoît Marchal also touts the virtues of separating out HTML from servlet logic.

Single Interface. Although you may have a tendency at first to build many servlets with many doPosts and doGets, for complex applications you may want to limit to just one dispatching servlet. And that's what's advocated and demonstrated by
Design Java servlets with the Delegation Event Model by Stephen Rao and Mary Xing, JavaWorld, Sep 1999.

Refactoring. Initially, you try to assign methods into classes according to responsibility. Java makes fairly easy to do this. One way is to have different classes perform various tasks: HTTP get/post processing, parameter parsing, output generation, database processing, and so on. If you are planning on writing something more than a small servlet, or even if you don't have any plans yet, refactoring responsibilities is a good idea.

Remember who owns what. The servlet you write can be used simulataneously by many users at the same time and each user of the servlet has a thread. Consider the user and the session one and the same. Avoid instance variables. An instance variable is any object owned by a a class. There will be only one of these per class - not one per user. In general, you can not have a user modify an instance variable because other users are also using the same variable.

Use non-shared object for elaborate applications. To build a complex servlet-based application where you would generally want to use UML and OO techniques, you need to have the servlet construct and then activate) a non-shared object. To create a non-shared object, instantiate it within a method:

doPost(HttpServlet Request req, HttpServletResponse resp)
throws ServletException, IOException {

NonSharedClass myclass = new NonSharedClass();
// myclass now processes the servlet request:
myclass.run(req, resp);

}

A non-shared object created this way can safely be object oriented - having its own instance variables. Use non-shared objects in this way to separate servlet logic from business logic.

You can store non-shared objects in sessions temporarily to preserve them for the user between servlet executions:

doPost(HttpServlet Request req, HttpServletResponse resp)
throws ServletException, IOException {

UserState isdoing = new UserState();
isdoing.justdid="visited page 1";
HttpSession session=req.getSession(true);
// JSDK 2.2 uses setAttribute(). For previous
// versions use putValue();
session.setAttribute("userstate", isdoing);

}

Later - possibly in a different servlet - you can retrieve the UserState object by upcasting it out of the session with HttpSession.getAttribute() - or getValue():

HttpSession session=req.getSession(false);

UserState myuserstate = (UserState) session.getAttribute("userstate");
// For previous versions use getValue()
String lastvisited = myuserstate.justdid;

Shared objects. Occasionally, you need to have objects that are shared among all users of a servlet. To create a shared object, set it up as in instance variable, and initialize it in the servlets init method:

SharedClass mysharedclass =null;
init() {

if (mysharedclass==null) {

mysharedclass = new SharedClass();

}

}
doPost(HttpServlet Request req, HttpServletResponse resp)
throws ServletException, IOException {

int x=mysharedclass.getX();

}

Remember that all instance variables of the shared object are shared. When setting values, you should use some kind of semaphore or synchronizing mechanism to serialize access among users.

Books

Highly Recommended get the O'Reilly book Java Servlet Programming by Hunter and Crawford. See also John Zukowski's Java servlet books: a comparative review, JavaWorld, Mar 2000.