intro servlets

41
Introduction to Java Servlet technology Skill Level: Introductory Roy W. Miller ([email protected]) Programmer Independent 07 Dec 2004 Java developer and trainer Roy Miller revamps our existing introductory servlet material into this single easy-to-follow, hands-on tutorial. Roy introduces explains what servlets are, how they work, how you can use them to create Web applications of any degree of sophistication you can imagine, and how you can use servlets most effectively as a professional programmer. Section 1. Before you start About this tutorial How do the pages you're reading in your favorite Web browser show up there? When you log into your favorite Web site, how does the Web site know that you're you? And how do Web retailers handle taking your order online? Those capabilities are possible because of code running on servers behind the scenes that interact with you in a Web session, access stored information throughout that process, and oftentimes present dynamic informatio n in one or more Web pages. The core of those capabilities is provided in the Java language world by servlets. The goal of this tutorial is to introduce you to servlets. It describes what servlets are, how they work, how you can use them to create Web applic ations of any degree of sophistic ation you can imagine, and how you can use servlets most effectivel y as a profes siona l programmer. The content of this tutorial is geared toward Java programmers who are unfamiliar, or only vaguely familiar, with servlets. It assumes a general knowledge of downloading and installing software, and a general knowledge of the Java language Introduction to Java Servlet technology  © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41

Upload: mohit-bhayana

Post on 08-Apr-2018

259 views

Category:

Documents


0 download

TRANSCRIPT

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 1/41

Introduction to Java Servlet technologySkill Level: Introductory

Roy W. Miller ([email protected])ProgrammerIndependent

07 Dec 2004

Java developer and trainer Roy Miller revamps our existing introductory servletmaterial into this single easy-to-follow, hands-on tutorial. Roy introduces explainswhat servlets are, how they work, how you can use them to create Web applicationsof any degree of sophistication you can imagine, and how you can use servlets mosteffectively as a professional programmer.

Section 1. Before you start

About this tutorial

How do the pages you're reading in your favorite Web browser show up there?When you log into your favorite Web site, how does the Web site know that you'reyou? And how do Web retailers handle taking your order online? Those capabilitiesare possible because of code running on servers behind the scenes that interactwith you in a Web session, access stored information throughout that process, andoftentimes present dynamic information in one or more Web pages. The core ofthose capabilities is provided in the Java language world by servlets. The goal of this

tutorial is to introduce you to servlets. It describes what servlets are, how they work,how you can use them to create Web applications of any degree of sophisticationyou can imagine, and how you can use servlets most effectively as a professionalprogrammer.

The content of this tutorial is geared toward Java programmers who are unfamiliar,or only vaguely familiar, with servlets. It assumes a general knowledge ofdownloading and installing software, and a general knowledge of the Java language

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 2/41

(creating classes, importing classes, etc.), but doesn't assume knowledge ofservlets. The tutorial includes a simple example to illustrate basic servlet concepts,and a more involved example that illustrates more sophisticated use of servlets in asmall contact management application.

Should I take this tutorial?

If you've been writing Web apps for a decade, this tutorial is not for you. If you don'tknow what servlets are, or are only vaguely familiar with them, keep reading. Thereis much more to servlets than what is included in this tutorial, but this is a good placeto start your learning.

You should, however, have the fundamentals of Java programming well in hand. Ifyou're not quite there yet, try my Introduction to Java programming tutorial to getstarted.

Tools and code

To run the examples or sample code in this tutorial, you'll need to have at least JDK1.4.2 or higher, along with the Eclipse IDE, installed on your machine. We'll walkthrough the process of installing the Tomcat plugin for Eclipse, which will allow youto develop servlet applications easily.

All code examples in this tutorial have been tested with J2SE 1.4.2 on the WindowsXP platform, but should work without modification using J2SE 1.4.1, or even 5.0.

To install Tomcat, go to the Jakarta Web site (see Resources) and download the

binary distribution of Tomcat 5.0.28 (the most current version that works with J2SE1.4.2, as of this writing). The package comes with a Windows installer that makesinstalling on that platform a breeze. Follow the instructions in the readme files, andyou'll be set.

To install the Tomcat plugin for Eclipse, go to the Sysdeo Web site (see Resources )and download the plugin zip file (tomcatPluginV3.zip, as of this writing). Then simplyextract it to your plugins directory, and follow the instructions at the bottom of thedownload page to set up the plugin. To be sure your plugin is working correctly, workthrough the very simple HelloWorld servlet setup "tutorial" that is linked at the bottomof the Sysdeo page (see Resources for a direct link).

Once you have Tomcat and the plugin installed, you're ready to begin this tutorial.

About the author

Roy Miller is an independent software development coach, programmer, and author.

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 2 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 3/41

He began his career at Andersen Consulting (now Accenture), and most recentlyspent three years using the Java platform professionally at RoleModel Software,Inc., in Holly Springs, NC. He has developed software, managed teams, andcoached other programmers at clients ranging from two-person start-ups to Fortune50 companies.

For technical questions or comments about the content of this tutorial, contact Royat [email protected].

Section 2. An introduction to servlets

What does a servlet do?When you use an interactive Web site, all that you see is what's in the browser.Behind the scenes, there's a Web server taking requests from you in a session,possibly handing off to other code (maybe on other servers) to process the requestand access data, and generating results to display in the browser.

A servlet is the gatekeeper for that process. It lives on the Web server and handlesincoming requests and outgoing responses. It has nothing to do with presentation,generally speaking, and really shouldn't. You can use a servlet to write to a stream that adds content to a Web page, but that's usually not a good idea either, because it

tends to encourage mixing presentation with business logic.

Servlet alternatives

Servlets aren't the only way to serve up Web pages. One of the earliest technologiesfor this purpose was the common gateway interface (CGI), but that forked aseparate process for each request, which wasn't very efficient. There were alsoproprietary server extensions like the Netscape Server API (NSAPI), but those were,well, proprietary. And in the Microsoft world, there is the active server pages (ASP)standard. Servlets provide an alternative to all of these, and they offer several

advantages:

• They're as platform independent as the Java language

• They give you full access to the entire Java language API, includinglibraries for data access (like JDBC)

• They're (in most cases) inherently more efficient than CGI, because

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 4/41

servlets spawn new threads, rather than separate processes, for requests

• There is extensive industry support for servlets, including containers formost popular Web and application servers

Servlets are a powerful addition to the professional programmer's toolbox.

But what is a servlet?

Most Java servlets that you'll encounter as a professional programmer are designedto respond to HTTP requests in the context of a Web application. As such, theHTTP-specific classes in the javax.servlet and javax.servlet.http

packages are the ones you'll care about.

When you create a Java servlet, you typically subclass HttpServlet. This classhas methods that give you access to the request and response wrappers you can

use to handle requests and create responses.

The HTTP protocol isn't Java-specific, of course. It is simply a specification thatdefines what service requests and responses have to look like. The Java servletclasses wrap those low-level constructs in Java classes with convenience methodsthat make them easier to deal with in a Java language context. When a user issuesa request via a URL, the Java servlet classes convert it to anHttpServletRequest and send it to the target pointed to by the URL, as definedin configuration files for the particular servlet container you're using. When the serverside has done its work, the Java Runtime Environment packages the results in anHttpServletResponse and then sends a raw HTTP response back to the client

that made the request. When you're interacting with a Web app, you usually makemultiple requests and get multiple responses. All of them are within the context of asession, which Java language wraps in an HttpSession object. You can accessthis object when you process requests, and add stuff to it when you createresponses. It provides some cross-request context.

A container, like Tomcat, manages the runtime environment for servlets. You canconfigure the container to customize the way in which the J2EE server functions,and you must  configure it to expose your servlets to the world. As we'll see, throughvarious configuration files in the container, you provide a bridge from a URL (enteredby a user in a browser) to the server-side components that handle the request that

you want the URL to translate into. When your app runs, the container loads andinitializes your servlet(s), and manages their lifecycle.

When we say that servlets have a lifecycle, we simply mean that things happen in apredictable way when a servlet is invoked. In other words, certain methods on anyservlet you create will always get called in the same order. Here's a typical scenario:

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 4 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 5/41

• A user enters a URL in his browser. Your Web server configuration filesays that this URL points to a servlet managed by a servlet containerrunning on your server.

• If an instance of the servlet hasn't been created yet (there's only one

instance of a servlet for an application), the container loads the class andinstantiates it.

• The container calls init() on the servlet.

• The container calls service() on the servlet, and passes in a wrappedHttpServletRequest and HttpServletResponse.

• The servlet typically accesses elements in the request, delegates to otherserver-side classes to perform the requested service and to accessresources like databases, then populates the response using thatinformation

• If necessary, when the servlet's useful life is done, the container callsdestroy() on the servlet to finalize it.

How do you "run" a servlet?

"Running" a servlet is like running a Java program. Once you've configured yourcontainer to know about the servlet, and to know that certain URLs should cause thecontainer to invoke the servlet, the container will call the lifecycle methods in theproscribed order. So, running a servlet essentially means configuring it correctly,then pointing a browser to the right URL. Of course, the code in the servlet is where

the interesting business logic happens. You don't have to worry about the low-levelstuff that's going on, unless something goes wrong.

Unfortunately, something does go wrong frustratingly often, especially when you'resetting up a servlet. The single biggest cause of headaches with servlet applicationsis configuration files. You can't effectively debug them. You simply have to get themright by trial and error, as you try to decipher the error messages that you may ormay not see in your browser.

Section 3. A simple servlet

What our simple servlet does

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 6/41

Our first servlet will do very little, but it will expose all of the basics of writing aservlet. The output will be some simple, unformatted text in a browser window:

Hello, World!

In creating this servlet, we'll be able to confirm that Tomcat functions as it ought to,and that we can use Eclipse to create a Web project like we should be able to. We'llalso walk through the process of configuring your Web app in the Tomcat servletcontainer, which can be a bear if you happen make a slight mistake in an XML file.Don't worry: In this tutorial, at least, it will all work.

In this first example, we'll write output to the browser directly from our servlet. Thiswill be the last time in the tutorial that we use that approach.

Setting up Eclipse

There are a few things we need to do to make sure we can create and manageTomcat projects in Eclipse.

If you've installed the plugin (by simply extracting the Sysdeo zip file to youreclipse/plugins directory), you should get some additional menu items and tools onyour toolbar. These are indicated in Figure 1.

Figure 1. Tomcat plugin features

The toolbar buttons let you start, stop, and restart Tomcat, which you'll have to dowhen you want to run your servlets.

To allow us to create Tomcat projects, which have the correct layout to facilitate

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 6 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 7/41

Tomcat deployment, we have to tell Eclipse a few things. If you clickWindow>Preferences, you'll see the standard Eclipse preferences dialog, with anew category called Tomcat at the bottom of the list. Clicking on that will show youthe main Tomcat preferences page (see Figure 2).

Figure 2. Tomcat preferences

Select Version 5.x, and specify the Tomcat home location. (On my system, thislocation is C:\Program Files\Apache Software Foundation\Tomcat 5.0, but yoursmay vary.) Select Context files as the context declaration mode. Then click on theJVM Settings preferences subcategory and make sure there's a valid JRE selectedin the drop-down menu at the top of the page. You can use the default JRE, or you

can point to your JDK, which you can tell Eclipse about in the Java>Installed JREspreferences page.

When you're done, click OK. We're now ready to create a Tomcat project.

Creating a Tomcat project

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 8/41

The Tomcat plugin makes life much easier for the Web developer using Tomcat. Ifyou click File>New>Project, and expand the Java wizard category in the dialog(see Figure 3), you'll see a new kind of a project wizard there: a Tomcat project.

Figure 3. New Tomcat project

Click Next, name the project "HelloWorld," then click Finish. If you switch to the

Java perspective in Eclipse, you'll be able to see that new project. It has a structurethat will facilitate deployment to Tomcat (see Figure 4).

Figure 4. Tomcat project structure

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 8 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 9/41

The work, WEB-INF, and WEB-INF/src directories are particularly important, as we'llsee later.

Testing Tomcat

Click the Start Tomcat toolbar button. Eclipse should update your console withinformational statements as Tomcat tries to launch. If it launches without showingany stack traces, you're set. If you see any stack traces in there, life becomesslightly more difficult. Unfortunately, trial and error (with your good friend Google) isthe only way to track down any errors that occur. The good news is that starting witha fresh, new project like we did should eliminate the possibility of any nasty errors.

When Tomcat starts, you won't see anything (except the console content). You'llhave to test it to be sure it's working. If you want a quick indication, try opening abrowser and entering the following URL:

http://localhost:8080/

If all goes well, you should see either a nice Tomcat welcome page, or a directorylisting for the Tomcat "ROOT context." Don't worry about the second one. We'llprove Tomcat is working when we run our first servlet.

Declaring the class

A servlet is a class, so let's create a basic one. In Eclipse, create a class calledHelloWorldServlet in your HelloWorld project. It should look like this:

public class HelloWorldServlet extends HttpServlet {

public void service(HttpServletRequest request,

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 10/41

HttpServletResponse response)throws ServletException, IOException {

PrintWriter writer = response.getWriter();writer.println("Hello, World!");writer.close();

}}

Enter this code, then press Ctrl+Shift+O to organize your import statements.Eclipse should give you imports for the following classes:

• java.io.IOException

• java.io.PrintWriter

• javax.servlet.ServletException

• javax.servlet.HttpServlet

• javax.servlet.HttpServletRequest

• javax.servlet.HttpServletResponse

Notice that we subclassed HttpServlet, and that we overrode the service()

method. The service() method is the most basic processing method that theservlet engine will call in our servlet's lifecycle. It takes a request wrapper and aresponse wrapper, which we can access in our method. We have no need to do sohere, though, since we're just doing something basic to get a servlet working. Wecould have overridden doGet(), but service() will give us what we need.

In our service() method, we called getWriter() on our response wrapper to

allow us to print a string literal to that stream. Then we closed the stream. That'stypical in a servlet that produces output: You perform the logic you need to perform,then you write to the output stream.

Configuring the Web application

The Java programming work is done, but now we have to do the necessary workwith the configuration files. In my opinion, this is the biggest headache of Webdevelopment. Fortunately, the Tomcat plugin takes away some of the pain.

Right-click on the HelloWorld project and select Properties. Select the Tomcatcategory of properties. You should see a context for the project that looks somethinglike this:

/HelloWorld

Now go look at the filesystem in your Tomcat home. Drill down to the

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 10 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 11/41

conf/Catalina/localhost subdirectory. There, you should see a set of XML files.Specifically, you should see a HelloWorld.xml file. Open that. This file defines a Webapplication context for Tomcat.

<Context path="/HelloWorld" reloadable="true"

docBase="path to your project\HelloWorld"workDir="path to your project\HelloWorld\work" />

When Tomcat launches, it reads these context files to tell the servlet containerwhere to find your classes (which include your servlets). If you look back at the INFOstatements Tomcat spits out to the console when it's loading, you'll see informationabout your Web application context in the list.

The last step for configuring your Web application in Tomcat is to create a web.xmlfile, which needs to live in the WEB-INF directory of your project. ( Note: Do not put itin the WEB-INF/src directory -- that's for other things.) Here's what the file should

look like for this simple example:

<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTDWeb Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>

<web-app><servlet>

<servlet-name>hello</servlet-name><servlet-class>HelloWorldServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello</url-pattern>

</servlet-mapping></web-app>

This file defines your Web application to Tomcat. The servlet-name elementnames your servlet for use in this file. The servlet-class element maps thatname to a particular class that defines the servlet -- HelloWorldServlet, in ourexample. The servlet-mapping element tells Tomcat that URLs of the form (inthis case) /hello map to our servlet, which is defined by the mapped servlet class.

Once we have this file in place, we can fire up Tomcat and see our servlet load.

Running the servlet

As I mentioned earlier, "running the servlet" simply involves starting Tomcat andpointing a Web browser to the URL that should invoke it. Start Tomcat using theappropriate toolbar button (you'll need to stop it and start again if it's alreadyrunning). Once Tomcat finishes launching, start a browser and enter the followingURL:

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 12/41

http://localhost:8080/HelloWorld/hello

You should see a nice message in your browser window.

Section 4. Action servlets

Introduction

In the early days of Web development, many professional programmers had tofigure out how to use servlets well as they went along. One of the most common

results was an explosion of servlets on the server. There was one for each type ofrequest.

That quickly became painful, so programmers started to include conditional logic intheir servlets to make them more adaptable, handling multiple types of requests.Over time, that also produced some ugly code. There's a better way, called an action servlet, which implements a concept called Model 2. As far as I know, this idea wasfirst written about by David M. Geary (see Resources for more from him) but hasbeen used well in popular servlet libraries, such as the Jakarta Struts project.

In an action servlet, you don't have conditional logic that directs the servlet's

behavior. Instead, you have actions (programmer-defined classes) that the servletdelegates to in order to handle different types of requests. Most of the time, that's amuch better object-oriented (OO) approach than having multiple servlets, or multipleif conditions in a single servlet.

What our sample action servlet does

Our sample action servlet will be the gatekeeper for a simplistic browser-basedapplication that will allow us to create, store, view, and delete contact list entries.Those entries will be nicely formatted. Eventually, users will have to log into the

application in order to use it, but we'll add that feature later, in Users and data .

Setting up the project

Create a new Tomcat project in Eclipse, just like you did for HelloWorld. Note thatthe name of your project is the default context value for the servlet, so you'll use it

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 12 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 13/41

when we enter the URL that accesses the servlet. If you configured Tomcat to usecontext files, it should automatically create one for this project.

Eclipse also should have created a project that has the correct structure, with thefollowing important directories:

• WEB-INF

• WEB-INF/src

• work

The first directory (WEB-INF) stores important configuration files, specifically theweb.xml file that we'll discuss later. It also contains our compiled code, in the classesdirectory. The second directory (WEB-INF/src) stores the source code for our Javaclasses. The third directory (work) contains the compiled code for our JavaServerPages (JSP) files, which Tomcat creates automatically for us whenever we hit a JSP

page for the first time after code has changed (we'll talk about JSP technology morein the next section). The root of the project contains all of our JSP source files, aswell as our database file.

Note that you can see all of this structure in the Resource perspective in Eclipse, butyou'll see only the WEB-INF/src and work directories in the Java Browsingperspective.

All of these files are contained in the contacts.jar file included with this tutorial (seeResources for a link). To import them, simply create a new Tomcat project, thenimport contacts.jar (use the Import>Zip file option). That will bring all of the files in

at the right locations, except the source code. The source code will end up in the srcdirectory at the root of the project. Move the contents of that folder to WEB-INF/srcand you should be all set.

Presentation

This is a tutorial about servlets, after all, which have almost nothing to do withpresentation. Still, without seeing some results on the screen somewhere, we'dreally be telling only part of the story. You certainly can write servlets that aren'tinvolved with presentation at all, but most Web apps present information in a

browser, which means that you have to choose a presentation mechanism to use.JavaServer Pages technology is one typical alternative and is used widely.

With JSP technology, you can create dynamic Web pages. They support staticHTML (or other markup, such as XML) and dynamic code elements that, as thename implies, can create content dynamically. Under the covers, JSP pages arecompiled into servlets (that is, into Java code) by a container like Tomcat. Youalmost never will have to care about that, however. Just know that the following flow

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 14/41

occurs:

• A user types a URL in a browser that the J2EE servlet container points toa servlet

• The servlet does its job and puts information in the session, or in a bean,and forwards to the JSP page

• The JSP code translates information in the bean and/or the session, andsends the response to the browser

You can create simple JSP pages easily and run them in Tomcat with only minorconfiguration changes in our Web app and without downloading additional codelibraries, so we'll use them here (see Resources for much more detailed informationabout JSP technology).

Our Contacts application will have one primary JSP page or listing existing contacts

and adding new ones. Later, we'll add pages for login and logout.

It's important to remember that JSP technology is just one presentation alternative.There are others. One that is gaining great popularity is the Jakarta Velocitytemplating package (see Resources). JSP technology does have a major drawback,which is that complicated, feature-rich apps tend to require ridiculously complex JSPpages, along with some extra server work to create custom tags  if you want to keepyour logic and presentation separate. Another drawback is that JSP technologyoffers a frequently irresistible temptation to mix business logic and presentation,which makes for brittle systems that bring on maintenance nightmares.

In my opinion, JSP technology is frequently the wrong choice, and Velocity (or someother templating approach) is frequently the right one. But for our simple example, itwill serve the purpose of illustrating the concepts we need to cover. In such a simplecase, mixing a little logic and a little presentation is acceptable. Professionally,however, it's unwise most of the time, even though many programmers do it.

The web.xml file

In order for us to use the JSP page we're about to create, we have to tell Tomcathow to handle it. To do that, we have to create a web.xml file in our WEB-INF

directory. It should look like this:

<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTDWeb Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>

<web-app><servlet>

<servlet-name>contacts</servlet-name><servlet-class>

com.roywmiller.contacts.model2.ContactsServlet</servlet-class>

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 14 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 15/41

</servlet>

<servlet-mapping><servlet-name>contacts</servlet-name><url-pattern>/index.htm</url-pattern>

</servlet-mapping>

<servlet-mapping><servlet-name>contacts</servlet-name><url-pattern>*.perform</url-pattern>

</servlet-mapping>

<servlet><servlet-name>jspAssign</servlet-name><servlet-class>

org.apache.jasper.servlet.JspServlet</servlet-class><init-param>

<param-name>logVerbosityLevel</param-name><param-value>WARNING</param-value>

</init-param><init-param>

<param-name>fork</param-name><param-value>false</param-value>

</init-param>

<load-on-startup>3</load-on-startup></servlet>

<servlet-mapping><servlet-name>jspAssign</servlet-name><url-pattern>/*.jsp</url-pattern>

</servlet-mapping></web-app>

We created a basic web.xml file for our HelloWorldServlet, but it was the prettyminimal. As your application becomes more complex, your web.xml file has tobecome more savvy. Let's analyze this file quickly.

The <servlet> tag specifies a name alias for our servlet that we'll use elsewhere in

the file. It also tells Tomcat which class to instantiate so as to create the servlet inmemory. In my Eclipse workspace, I created acom.roywmiller.contacts.model2 package to hold the servlet class. You cancall your package whatever you want, but the path to your servlet has to matchwhat's in your <servlet-class> element here. The second servlet we define isone that comes with Tomcat when you download it, and you don't need to change it.It's simply the JSP-handling servlet.

The <servlet-mapping> tells Tomcat which servlet to execute when certainURLs come to the server. We have three mappings here. The first maps the defaultpage that the Web server looks for (<index.htm>) to our servlet. The second tells

Tomcat to map any URL ending in .perform to our servlet. URLs of that form willtell our servlet which action to implement (we'll discuss how this works in more detaillater). The third mapping tells Tomcat to use the JSP servlet to handle JSP pages.

The user view of the JSP page

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 16/41

In our simple example, we're not going to spend much time talking about JSPtechnology. That's to ensure that we keep things simple, and don't get bogged downin the details of presentation generally and JSP technology in particular. (Again, seeResources for more information.) We're also going to put everything on a singlepage, at least initially, even though that's somewhat unrealistic. That should

minimize the number of pages we have to create just to illustrate the importantconcepts of using servlets.

Our initial page will present the list of contacts, which will come from an object thatcontains the list. It will also contain a form for adding a new contact. The page willlook like Figure 5.

Figure 5. ContactList page

While not a work of art, the page displays all of our contacts in nicely formatted rowsat the top. Each one has a Delete link that the user can click on to delete thatparticular contact. The form contains fields for name and address values, and radiobuttons for the type of contact (family or acquaintance, in our simple example). This

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 16 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 17/41

simple page will allow us to explore how to use a simple action framework in ourservlet application. It also will let us explore how to use the request and responseour servlet receives from the browser during a user session.

Now we're ready to create the page.

Coding the JSP page

Here's the code for our JSP page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><%@ page import="java.util.*" %><%@ page import="com.roywmiller.contacts.model.*" %><html><head><title>Contacts List 1.0</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">body, table, hr {

color: black;background: silver;font-family: Verdana, sans-serif;font-size: x-small;

}</style>

</head>

<body><jsp:useBean id="contacts" scope="session"

class="com.roywmiller.contacts.model.ContactList"/>

<h2>Contact List 1.0</h2>

<hr size="2"/><table frame="below" width="100%">

<tr><th align="left"></th><th align="left">Name</th><th align="left">Street</th><th align="left">City</th><th align="left">State</th><th align="left">Zip</th><th align="left">Type</th>

</tr><%

List list = contacts.getContacts();for (Iterator i = list.iterator(); i.hasNext();) {

Contact contact = (Contact)i.next();%>

<tr><td width="100"><a href="removeContactAction.perform?id=<%= contact.getId()%>"

>Delete</a></td><td width="200"><%

=contact.getFirstname()%> <%=contact.getLastname()%></td><td width="150"><%=contact.getStreet()%></td><td width="100"><%=contact.getCity()%></td><td width="100"><%=contact.getState()%></td><td width="100"><%=contact.getZip()%></td><td width="100"><%=contact.getType()%></td>

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 18/41

</tr><%

}%></table><br/><br/><br/><fieldset>

<legend><b>Add Contact</b></legend><form method="post" action="addContactAction.perform">

<table><tr>

<td>First Name:<td><td><input type="text" size="30"

name="firstname"></td></tr><tr>

<td>Last Name:<td><td><input type="text" size="30"

name="lastname"></td></tr><tr>

<td>Street:<td>

<td><input type="text" size="30"name="street"></td></tr><tr>

<td>City:<td><td><input type="text" size="30"

name="city"></td></tr><tr>

<td>State:<td><td><input type="text" size="30"

name="state"></td></tr><tr>

<td>Zip:<td><td><input type="text" size="30"

name="zip"></td>

</tr><tr>

<td>Type:<td><td><input type="radio" size="30"

name="type" value="family">Family <input type="radio" size="30"

name="type" value="acquaintance"checked> Acquaintance</td>

</tr></table><br/><input type="submit" name="addContact" value=" Add ">

</form></fieldset>

</body></html>

At this point, most of what you see there is probably Greek. We won't dissect all of it,but over the next few sections we'll hit the high points for understanding how ourservlet will interact with this page.

Anatomy of a simple JSP page

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 18 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 19/41

In a JSP page, HTML is HTML. Java code embedded in the page appears like so:

<% Java code %>

In order to embed Java code in the page, you have to tell the JSP page where theclasses are, just like you do in a Java class. You do that with statements like this:

<%@ page import="java.util.*" %>

Our page displays a list of contacts, which come from a ContactList instance thatthe JSP page knows about because of this line:

<jsp:useBean id="contacts" scope="session"class="com.roywmiller.contacts.model.ContactList"/>

This line tells the JSP page to use a bean, called contacts elsewhere in the page.It's an instance of com.roywmiller.contacts.model.ContactList, and ithas session scope.

Notice that we have a Java for loop in the body of the page:

List list = contacts.getContacts();for (Iterator i = list.iterator(); i.hasNext();) {

Contact contact = (Contact)i.next();%>

<tr>

<td width="100"><a href="removeContactAction.perform?id=<%=

contact.getId()%>" >Delete</a></td><td width="200"><%=contact.getFirstname()%> <%=

contact.getLastname()%></td><td width="150"><%=contact.getStreet()%></td><td width="100"><%=contact.getCity()%></td><td width="100"><%=contact.getState()%></td><td width="100"><%=contact.getZip()%></td><td width="100"><%=contact.getType()%></td>

</tr><%

}

This illustrates how JSP technology lets you mix HTML and Java statements. Here

we loop through the contact list of our contact object. Each time through the loop,we add a <tr> element to our HTML table. Within each row of the table, one percontact, we call getters on the Contact instance to populate our table cells. For thefirst cell, we need to create a Delete link for each row. We set the href attribute tothe following string:

removeContactAction.perform?id=<%= contact.getId()%>

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 20/41

When a user clicks that link, that string will be appended to the end of the URL thatgets sent to the server, after an initial slash (/) is added. The question mark is adelimiter for request parameters, which follow in name=value pairs. In this case, wesend along the ID of each contact.

This same kind of thing happens elsewhere in the page, such as in the form to add anew contact. Notice the <form> tag:

<form method="post" action="addContactAction.perform">

When a user clicks the Add button (the submit button at the bottom of the form),addContactAction.perform gets appended to the URL.

That's all there is to it! Some of this syntactical magic is part of the reason many

professional programmers either begrudgingly use JSP technology, or createvarious helper classes (such as custom JSP tags) that help make pages easier tocreate, read, and maintain. But now that we have the page, we can get to writingsome code.

Creating the servlet

Our servlet is similar to HelloWorldServlet, with the addition of our actionhandling capability:

import java.io.IOException;

import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import com.roywmiller.contacts.actions.Action;

public class ContactsServlet extends HttpServlet {

protected ActionFactory factory = new ActionFactory();

public ContactsServlet() {super();

}

protected String getActionName(HttpServletRequest request) {String path = request.getServletPath();return path.substring(1, path.lastIndexOf("."));

}

public void service(HttpServletRequest request, HttpServletResponse response)throws

ServletException, IOException {Action action = factory.create(getActionName(request));

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 20 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 21/41

String url = action.perform(request, response);if (url != null)

getServletContext().getRequestDispatcher(url).forward(request, response);}

}

We extend HttpServlet and override the service() method, just like before. Inthat method, we:

• Derive the action name from the URL that caused the servlet to beinvoked

• Instantiate the correct action based on the name

• Tell the action to perform itself

• Forward the response to the URL to which our action points us

We derive the action name from the URL that caused the servlet to be invoked,which we get from request.servletPath(). Remember that all of the URLs thatcause us to invoke an action will have the form *.perform. We parse that to getthe string to the left of the dot, which is the action name, then pass that action nameto our ActionFactory to instantiate the right action. Now you see why we told ourWeb app how to handle URLs of that form, and why we used those "magic" stringsin our JSP page. It was so we could decode them here and use actions to ouradvantage. What's the alternative? Lots and lots of if statements, and lots of extracode. With actions, as we'll see, each action we need to perform is neatlyencapsulated.

This is fine, but we need some additional classes to get the job done. That's whereour action framework comes in.

A simple action framework

Our simple action framework has four main components:

• An ActionFactory. This factory translates action names in requests toaction classes our servlet can use to do work.

• An Action interface. This interface defines the very simple publicinterface of all actions.

• An abstract class called ContactsAction. This class implements onemethod common to all actions, and forces subclasses to implement theother (perform()).

• Three subclasses of ContactsAction. These subclasses enable ourservlet to bootstrap itself, add new contacts, and remove contacts.

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 22/41

In the service() method of our servlet, the process begins with ActionFactory.

The ActionFactory

Here's our ActionFactory:

import java.util.HashMap;import java.util.Map;import com.roywmiller.contacts.actions.Action;import com.roywmiller.contacts.actions.AddContactAction;import com.roywmiller.contacts.actions.BootstrapAction;import com.roywmiller.contacts.actions.RemoveContactAction;

public class ActionFactory {protected Map map = defaultMap();

public ActionFactory() {super();

}

public Action create(String actionName) {Class klass = (Class) map.get(actionName);if (klass == null)

throw new RuntimeException(getClass() + " was unable to findan action named '" + actionName + "'.");

Action actionInstance = null;try {

actionInstance = (Action) klass.newInstance();} catch (Exception e) {

e.printStackTrace();}

return actionInstance;}protected Map defaultMap() {

Map map = new HashMap();

map.put("index", BootstrapAction.class);map.put("addContactAction", AddContactAction.class);map.put("removeContactAction", RemoveContactAction.class);

return map;}

}

An ActionFactory is quite simple. It has a Map of action classes and their names.We use the names in our pages to tell our servlet which actions to perform. In ourcase, we have three actions:

• BootstrapAction

• AddContactAction

• RemoveContactAction

Recall that the actions to add and remove contacts were sent as URLs to our servletby the Add form and the Delete link, respectively. The BootstrapAction simply

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 22 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 23/41

fits the calling of /index.htm into our action framework.

When we tell the factory to create an Action, it instantiates the class and gives usback the instance. Adding a new action to the factory is as simple as creating theclass for the action, then adding a new entry in the factory's action Map.

Actions

The Action interface looks like this:

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public interface Action {public String perform(HttpServletRequest request, HttpServletResponse response);public void writeToResponseStream(HttpServletResponse response, String output);

}

The method we'll be using extensively now is perform(). The other method,writeToReponseStream(), allows an action to write directly to the output streamof the response, for passthrough to the JSP page. Whatever gets written (text,HTML, etc.) shows up on the page. We won't be using that method for the moment,but it's available on ContactsAction for you to see how it's done. Remember thatwe used the code in the body of this method in our HelloWorldServlet, so itshouldn't be unfamiliar to you.

Starting up with BootstrapAction

The simplest subclass of ContactsAction we have is BootstrapAction, andit's a good pattern for the others:

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class BootstrapAction extends ContactsAction {public String perform(HttpServletRequest request,

HttpServletResponse response) {return "/" + "contactList.jsp";

}}

We simply implement perform() to do what we want. In this case, all we do isreturn a URL that points to contactList.jsp (the initial slash is important, so don'tforget it). Now look back at the service() method on ContactsServlet:

public void service(HttpServletRequest request, HttpServletResponse response)

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 24/41

throws ServletException, IOException {Action action = factory.create(getActionName(request));String url = action.perform(request, response);if (url != null)

getServletContext().getRequestDispatcher(url).forward(request, response);}

Our action either returns a URL string or writes to the output stream for printing onthe JSP page. If our action returns a URL string, which our BootstrapAction

does, we get the ServletContext, ask it for a RequestDispatcher on our URL,and finally forward the request and response to the JSP servlet so it can constructthe page. Our action servlet regains control after that, and can do any remainingwork, as long as it doesn't write to the JSP page's PrintStream, which is nowclosed.

We could call sendRedirect() on our response if we wanted to, rather thanusing a RequestDispatcher:

response.sendRedirect("http://...");

But there's a price to pay for doing that. When we use a dispatcher, we're delegatingthe request and response to the JSP servlet, which also forwards the existingHttpSession. That preserves the contents of the session. Forwarding to anotherURL wouldn't. At the moment, when we're displaying the page initially, there'snothing in the session that we care about, so the effect would be the same. But verysoon it will be important to preserve the session contents.

To tell our action framework about this new available action, we added this line to

the factory's action Map:

map.put("index", BootstrapAction.class);

Adding contacts

An app that shows a page that doesn't let you do anything isn't very useful. We needto be able to add contacts.

To do that, we must:

• Create a class called AddContactAction

• Implement perform() to add a new Contact instance to theContactList we maintain in our Web session

• Tell the factory about the new action

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 24 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 25/41

Telling the factory about the action is as simple as adding another entry in thefactory's map, as we did with BootstrapAction.

The AddContactAction class, with its perform() method implemented, lookslike this:

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;

import com.roywmiller.contacts.model.Contact;import com.roywmiller.contacts.model.ContactList;

public class AddContactAction extends ContactsAction {

public String perform(HttpServletRequest request, HttpServletResponse response) {Contact newContact = createContact(request);

HttpSession session = request.getSession();ContactList contacts = (ContactList) session.getAttribute("contacts");contacts.addContact(newContact);session.setAttribute("contacts", contacts);

return "/contactList.jsp";}

protected Contact createContact(HttpServletRequest request) {Contact contact = new Contact();contact.setFirstname(request.getParameter(RequestParameters.FIRSTNAME));contact.setLastname(request.getParameter(RequestParameters.LASTNAME));contact.setStreet(request.getParameter(RequestParameters.STREET));contact.setCity(request.getParameter(RequestParameters.CITY));contact.setState(request.getParameter(RequestParameters.STATE));contact.setZip(request.getParameter(RequestParameters.ZIP));contact.setType(request.getParameter(RequestParameters.TYPE));

return contact;

}}

All we do here is call createContact() to create a new Contact and set itsinstance variables to the corresponding values containing the request parameters.Then we add the new Contact to the ContactList in the HttpSession. Finally,we tell our servlet to return to /contactList.jsp.

Recall that every time we create a Contact, the constructor assigns it a unique ID.Look back at the JSP code for a moment. You'll see two important things in it withregard to what we're doing in this action. First, notice that we guaranteed we'dalways have a ContactList instance in our session by adding this line:

<jsp:useBean id="contacts" scope="session"class="com.roywmiller.contacts.model.ContactList"/>

When the JSP page is first compiled and displayed (as a result of forwarding to theJSP page after BootstrapAction performs), it will instantiate a ContactList.

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 26/41

This object has nothing in it, which is why our list of contacts shows up empty whenwe start the app. In AddContactAction, we're modifying that object to add newcontact information, then reinserting it in the session. When the page displays afterthat, it will read the ContactList's list of Contact instances and display them.

Second, notice that our form to add contacts looks like this:

<form method="post" action="addContactAction.perform">

table with labels and text input fields

<input type="submit" name="addContact" value=" Add "></form>

The action for the form causes addContactAction.perform to be sent in therequest to our servlet. It then extracts the addContactAction portion as the actionname, looks it up in the factory, and creates an instance of AddContactsAction.

Removing contacts

Adding contacts is nice, but being able to remove them is just as important. Beingable to edit them would be nice, but this tutorial is only so long. Besides, adding editcapability would be as simple as adding another action. So for now, we'll just add theability to remove contacts and then move on to more interesting things.

As before, all we have to do is add a new action class, implement its perform()

method, and tell the factory about it. We also have to be sure that our JSP code tells

our servlet to invoke the action at the right time.

Look at the Delete link for each row of the contacts table in our JSP page:

<a href="removeContactAction.perform?id=<%=contact.getId()%>" >Delete</a>

That link tells our servlet to ask the factory for the right action class for the nameremoveContactAction. It also passes a parameter called id in the request, witha value set to the current contact's ID.

Our class looks like this:

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;

import com.roywmiller.contacts.model.ContactList;

public class RemoveContactAction extends ContactsAction {

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 26 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 27/41

public String perform(HttpServletRequest request, HttpServletResponse response) {int contactId = Integer.parseInt(request.getParameter("id"));

HttpSession session = request.getSession();ContactList contacts = (ContactList) session.getAttribute("contacts");contacts.removeContact(contactId);session.setAttribute("contacts", contacts);

return "/contactList.jsp";}

}

All we do here is grab the id parameter and the ContactList from the session,tell the list to remove the Contact with that id, then replace the list on the session.Last, but not least, we tell the servlet to forward back to contactList.jsp.

Running the app

If curiosity hasn't gotten the better of you already, you should now run the app to seehow it works.

Launch a browser and enter the following URL:

http://localhost:8080/contacts/

If Tomcat works its magic correctly, you should be looking at contactList.jsp, with nocontacts in the list. Type in some values for the text fields on the add form and clickthe Add button. You should see a new contact in the list, complete with a Delete link

to the left of the contact's name. Unless you changed it, its type should be set toAcquaintance (the default radio button selection for type). To keep things simple, wedidn't do any validation of the form, so you can enter multiple contacts with exactlythe same values for all fields. Each contact has a unique ID, so each one will showup separately, and you can delete them individually.

That's it -- we have a working Web application! But we can't save our list of contacts,so we have to reenter them every time we launch the app. Worse, every user of ourapp has the same list of contacts. We can fix that by adding support for uniqueusers, and by storing data in a file (the simplest database that could possibly work).We'll do both in the next section.

Section 5. Users and data

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 28/41

Enhancing the app

In this section, we're going to refactor our code and our existing JSP page somewhatto handle persistent contact data for unique users. In a nutshell, we'll do thefollowing:

• Create a ContactsUser object

• Give each ContactsUser a username, password, and contact list

• Change our JSP page's <jsp:useBean/> tag to use a ContactsUser

• Add login.jsp as the first page of the app

• Change contactList.jsp to include a friendly welcome message for thelogged-in user

• Add a Logout link to contactList.jsp to invoke LogoutAction

• Add a goodbye.jsp to display a personalized goodbye message

• Add a LoginAction and a LogoutAction

• Add a UsersDatabase to handle storing and retrieving Contacts fromusersDatabase.txt

• Initialize the ContactsDatabase by overriding init() on our servlet

• Override destroy() on our servlet to tell UsersDatabase to close

usersDatabase.txtNot so bad, really. The only real new concepts are using files (just more standardJava language work) and directing to new pages. All of the action handlingmechanisms are the same. This will illustrate the power of our action framework,which took precious little time to create. And it isn't nearly as complicated assomething like Jakarta's Struts framework (see Resources), which just might beoverkill for what you're doing in your application.

The ContactsUser

Our ContactsUser object looks like this, minus the import statements andaccessors (you can find the complete source code in contacts.jar):

public class ContactsUser {

protected String username = "";protected String password = "";protected List contactList = new ArrayList();

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 28 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 29/41

public ContactsUser() {}

public ContactsUser(String username, String password, List contactList) {this.username = username;this.password = password;this.contactList.addAll(contactList);

}

public boolean hasContacts() {return !contactList.isEmpty();

}

public void addContact(Contact aContact) {contactList.add(aContact);

}

public void removeContact(Contact aContact) {contactList.remove(aContact);

}

public void removeContact(int id) {Contact toRemove = findContact(id);

contactList.remove(toRemove);}

protected Contact findContact(int id) {Contact found = null;

Iterator iterator = contactList.iterator();while (iterator.hasNext()) {

Contact current = (Contact) iterator.next();if (current.getId() == id)

found = current;}return found;

}

accessors...}

This class holds information about users of the application. For the most part, that'sall it does. It holds the user's username and password, and maintains a list ofcontacts for the user. It allows various actions in our action framework to addContacts to the user, and remove them. The no-argument constructor is there forunit testing purposes. The other constructor, the one that takes three arguments, isthe one the app uses.

You might be asking yourself, "Why doesn't this class have a ContactList

instance variable?" After all, we went to the trouble of creating it in the first place.Why don't we use it? The simple answer is that we really don't need that class

anymore. It wrapped an ArrayList and gave us some helper methods. Thosehelper methods really make more sense on ContactUser. If we used aContactList, we'd be calling methods on it from ContactUser that have thesame names, and that we want to accomplish the same thing. For example, ifContactUser had a ContactList, and we named that instance variablecontactList, here's what addContact() would look like:

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 30/41

public void addContact(Contact aContact) {contactList.addContact(aContact);

}

Delegating to that other object here is a little silly. So we deleted the ContactList

class. That's what refactoring is all about. We simplified our code, and reduced thenumber of classes in our system, but still got the same job done. HavingContactList was an intermediate step in creating our system. It let us get up andrunning, and helped us create our action framework. Then its useful life ended andwe got rid of it. Just because you wrote some code doesn't mean you have to keep itaround forever.

Changing contactList.jsp

Changing the JSP page to use our new ContactUser is straightforward. There are

three changes we need to make.

The first is to change the <jsp:useBean> tag to look like this:

<jsp:useBean id="user" scope="session"class="com.roywmiller.contacts.model.ContactsUser"/>

Now our page will instantiate a ContactsUser instead of a ContactList.

The second change is to update the table row-building logic in the page to use ournew user variable:

<%List list = user.getContacts();for (Iterator i = list.iterator(); i.hasNext();) {

Contact contact = (Contact)i.next();%>

The third change is to add a link for a user to log out:

<a href="logoutAction.perform">Logout</a>

We'll put this link next to the "Contacts 1.0" header. When a user clicks the link, ourservlet will perform the LogoutAction.

Adding the login/logout pages

Compared to our other pages, the ones to support logging in and logging out are

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 30 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 31/41

simple. The only differences exist within the <body> tag. Here's login.jsp:

<body><h2>Contact List 1.0</h2><hr size="2"/><fieldset>

<legend><b>Please Login</b></legend><form method="post" action="loginAction.perform">

<table><tr>

<td>Username:<td><td><input type="text" size="30" name="username"></td>

</tr><tr>

<td>Password:<td><td><input type="text" size="30" name="password"></td>

</tr></table><br/><input type="submit" name="login" value=" Login ">

</form></fieldset>

</body>

This page has a form with two text fields and a submit button. When a user clicksLogin, our servlet will perform the LoginAction.

Here's goodbye.jsp:

<body><jsp:useBean id="user" scope="session"

class="com.roywmiller.contacts.model.ContactsUser"/>

<h2>Contact List 1.0</h2><hr size="2"/>Goodbye <%= user.getUsername() %>!</body>

This page calls getUsername() on a ContactsUser bean to display apersonalized goodbye message.

When a user tries to log in with a username and password that aren't in ourdatabase, our application gives up and routes the user to an error page, which lookslike this:

<body><h2>Contact List 1.0</h2><hr size="2"/><fieldset><legend><b>Error</b></legend>There was an error: <%= session.getAttribute("errorMessage") %></fieldset></body>

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 32/41

This is the simplest page we have. It uses the default session variable available inall JSP pages to display an error message.

Adding LoginAction

The LoginAction class looks like this:

public class LoginAction implements Action {

public String perform(HttpServletRequest request, HttpServletResponse response) {String username = request.getParameter(USERNAME);String password = request.getParameter(PASSWORD);

ContactsUser user = UserDatabase.getSingleton().get(username, password);if (user != null) {

ContactsUser contactsUser = (ContactsUser) user;request.getSession().setAttribute("user", contactsUser);return "/contactList.jsp";

} elserequest.getSession().setAttribute("errorMessage", "Invalidusername/password.");

return "/error.jsp";}

}

This action grabs the username and password parameters from the request, thenchecks to see if our database contains a user with that username/passwordcombination. If it does, we put the user in the session and go directly tocontactList.jsp. If that user doesn't exist in our database, we set an error messageon the session and go to error.jsp.

Adding actions should be easy for us now. We add an entry to our action factory thatlooks like this:

map.put("loginAction", LoginAction.class);

With the pages in place, and our factory aware of our new action, we're done. Youshould be able to run the app and see the login page. When you enter a usernameand password, regardless of what they are, you should see the error page. In just alittle while, you'll be able to log in with a valid username and password, and seecontactList.jsp with an empty contact list.

Adding LogoutAction

The LogoutAction class looks like this:

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 32 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 33/41

public class LogoutAction implements Action {

public String perform(HttpServletRequest request, HttpServletResponse response) {UserDatabase.getSingleton().shutDown();return "/goodbye.jsp";

}

}

Here we tell our database to shutDown(). That method on UserDatabase lookslike this:

public void shutDown() {writeUsers();

}

protected void writeUsers() {StringBuffer buffer = new StringBuffer();Collection allUsers = users.values();Iterator iterator = allUsers.iterator();while (iterator.hasNext()) {

ContactsUser each = (ContactsUser) iterator.next();UserRecord record = new UserRecord(each);buffer.append(record.getFullRecord());

}writeText(buffer.toString());

}

protected synchronized void writeText(String text) {Writer writer = null;

try {writer = new FileWriter(usersFile.getAbsolutePath());writer.write(text);

} catch (Exception e) {throw new RuntimeException("Unable to append to file.", e);

} finally {

closeWriter(writer);}}

shutDown() calls writeUsers(), which iterates over all the users we have inmemory (from when we read in the file when the servlet initialized itself), creates aUserRecord for each, then passes the complete string to writeText(). Thatmethod dumps the string to the file, overwriting the existing contents. TheUserRecord class is a nice helper that encapsulates all of the somewhat messytokenizing work for each user record in the file. You can examine the code foryourself (see contacts.jar for the complete source code listing).

Once the database is shut down, we tell the servlet to forward to goodbye.jsp todisplay our personalized goodbye.

The userDatabase.txt file

Most Web applications access data from a "database" of some kind. Many use an

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 34/41

industrial-strength RDBMS, but a text file can be a database also. It's the simplestdatabase that could possibly work. If you wrap it well, and hide the access detailsbehind an interface that makes accessing the data reasonably painless for otherclasses in your app, the form of the underlying data store really doesn't matter.

In our application, we'll use a text file. That file will contain a single line per user, inthe following form:

username passwordcomma-delimited contact1 info|comma-delimited contactN info|...

The usernames in our file will be plain text, but the passwords will be Base64encoded for (arguably too-simple) security. The entries for contacts will becomma-delimited within each. The contacts themselves will be delimited by pipecharacters (|). There's no magic to this formatting. It just does what we need it to do,which is to allow us to parse the file easily.

For convenience, we'll put this file at the root of our project so that the path to the fileis straightforward.

To keep things simple, our application doesn't support user maintenance features,which means that there's no way to add or remove a user from within the app. Thatmeans that you have to add users to userDatabase.txt manually. For example, toadd a user named testuser with the password password, add the following lineto the file:

testuser cGFzc3dvcmQ=

The password in each entry is encoded with Base64 encoding. You can use theEncoderDecoder class in contacts.jar to figure out the encoded version of yourpassword. Its main() method lets you enter a plaintext string, then run the class toprint the encoded password to the console.

The UserDatabase

Our UserDatabase wraps interaction with our text file. The class listing looks large,

but it's not complicated (much of the perceived complexity is the extra Java codingstuff you need to deal with reading and writing files). We'll discuss a few high pointsin this section (see contacts.jarfor the complete code listing).

The class implements the Singleton pattern. The class maintains a single instancethat all users share by calling getSingleton().

The class maintains a Map of ContactsUsers, with the concatenated username

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 34 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 35/41

and password acting as the key for each entry. Anything could serve as the key, butthis was convenient.

In our servlet init() method, we'll tell the UserDatabase where the database fileis located (based on the ServletContext), then we'll tell it to initialize itself by

calling initialize(). That method looks like this:

public void initialize() {usersFile = new File(databaseFilePathname);

String allUsers = retrieveText();StringTokenizer tokenizer = new StringTokenizer(allUsers, "\n");while (tokenizer.hasMoreTokens()) {

String userEntry = tokenizer.nextToken();UserRecord record = new UserRecord(userEntry);put(new ContactsUser(record.getName(), record.getPassword(),

record.getContactList()));}

}

This method reads in the complete file by calling retrieveText, tokenizes the bigstring, creates a UserRecord for each user, then calls put() to place the newContactsUser in the map. The real work of this method goes on in the calls toretrieveText() and put():

protected synchronized String retrieveText() {BufferedReader bufferedReader = null;

try {bufferedReader =

new BufferedReader(new FileReader(usersFile.getAbsolutePath()));char charBuff[] =

new char[(int) new File(usersFile.getAbsolutePath()).length()];

bufferedReader.read(charBuff);return new String(charBuff);

} catch (Exception e) {throw new RuntimeException("Unable to read in the file.", e);

} finally {closeReader(bufferedReader);

}}

protected void closeReader(BufferedReader bufferedReader) {try {

if (bufferedReader != null)bufferedReader.close();

} catch (Exception ex) {}}

public void put(ContactsUser user) {String userKey = user.getUsername() + user.getPassword();users.put(userKey, user);

}

The retrieveText() method does the file reading work. It creates aBufferedReader to read the entire file contents into a character buffer, which is

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 36/41

then turned into a String. In its finally clause, it calls closeReader() to do just that. The writeText() method writes output to the file, overwriting its existingcontents. The method hides the same kind of file interaction details.

The put() method creates the key for the user (the username plus the password)

and inserts it in the map of users.

Section 6. Using servlets effectively

Introduction

In this tutorial, we've only scratched the surface of what you can do with servlets.Web apps can be as sophisticated as you can imagine. The underlying mechanisms,though, are essentially the same for all of them, and if you're writing code in the Javalanguage, servlets are at the core. Creating more sophisticated apps is a matter ofusing more sophisticated tools and libraries.

However, that's where many programmers make mistakes that lead them to createterrible Web applications. This section contains some suggestions on how to avoidthat. Most Java programmers with Web development experience would agree withsome of these. Some are more controversial. In any case, they should help get youstarted with servlets well.

Use a single servlet

If you can't use just one servlet, use as few as possible. In fact, I suggest that youuse one until you absolutely can't anymore. You don't need a hundred servlets. Youcertainly don't need one for each type of request.

Don't hang around the servlet

Spend as little time in your servlet as possible.

Servlets aren't a place for business logic. That's bad OOP design. Think of a servletas one of two things:

• An extra layer behind your UI that helps get "events" to the server

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 36 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 37/41

• An extra layer in front of the server that allows you to use a browser asyour UI

Either way, it's a place where you quickly dispatch matters to other pieces of yourapplication, then get out.

Use actions

An action framework, even a simple one like the one we used in this tutorial, is apowerful approach. It allows you to follow my previous bit of advice: to spend as littletime in your servlet as possible. It's also good OOP design. Each action class doesone thing, or a very cohesive set of related things.

Some people think this fragments the code, making it more difficult to understand. Ithink that this objection stems from two things:

• People aren't used to looking at object-oriented code, which certainly canfeel more fragmented when you first start looking at it

• People favor more procedural code, even in an object

Think about the alternative. Without actions (assuming you don't simply delegate toother objects that you don't call "actions"), you'll have to have lots of if statements.If you have two or three, your code will be reasonably easy to read. If you have ten,that's silly. A method that requires you to scroll through several screens is bad news.It usually means that the method does too much. At minimum, you should extract theaction-like things you do in service() (or doGet(), etc.) into other methods thatare named well so you know what they do.

Use actions. When you need to add features, add actions.

Use service(), unless you can't

There are many folks in the servlet world who claim that you shouldn't overrideservice(). Instead, they say, you should override doGet() and/or doPost(),possibly having them call each other, making your code look something like this:

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {statements

}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);

}

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 38/41

I don't know where these ideas come from. Bruce Eckle suggests that it's a holdoverfrom the CGI days, when folks grew used to paying attention to whether a GET orPOST was coming in. (See Resources for a link to a more detailed version of histheory.) I've never heard a good reason not to use service(). In any case, if you

use it, and then determine later that it would be better to use one of the doX()flavors, refactor the code! Until then, use service(), because it's easier.

Don't mix presentation and business logic

Generating complex HTML strings to spit out to the JSP page's print stream is finefor a simple app, but creating a more feature-rich app that way is more painful than itneeds to be.

It's wiser to keep presentation in the place where it belongs: in the page. JSP

technology allows you to do that, but as I said earlier, it requires a lot more work tokeep business logic and presentation separate. Templating engines like Velocity areoften a better choice. Whatever approach you choose, minimize the mixing ofbusiness logic and presentation.

Handle exceptions well

We didn't talk about this much in this tutorial, but handling exceptions becomesimportant when you're creating a Web app. There is nothing more frustrating to theuser than having something unexpected happen on the server side, and then seeing

a cryptic stack trace in your browser. Some of those traces can be disgustinglyobtuse, and obscure. Tracking them down can be frustrating.

Many of the packaged Web app development libraries, like Struts (see Resources),come with built-in frameworks for handling dynamic display of messages, includingerrors. Use those features.

Don't use every feature

Do you need to use every single feature of the Web app development framework or

library you're using? Probably not, and using every one can make your code muchmore complex than it needs to be. In fact, I recommend that you not start with aframework at all, except the simplest one that could possibly work. Sometimes thatfeature or framework you "know" you'll be using or need to use ends up beingextreme overkill for the problem at hand.

Use a framework when it's wise to use one. Don't assume that you need it. Wait foryour system to tell you that you do. Some programmers consider that "bad design."

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 38 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 39/41

Not so. Assuming you'll need a particular framework, or even a particular feature ofthat framework, can be overdesign. You should design for what you need; mostoften, that changes as the system grows. It's frustrating to pick a framework beforedevelopment begins, then hit a brick wall because that framework doesn't support orallow something you want to do.

Section 7. Summary

Conclusion

In this tutorial, you've learned about Java servlets, and how to use them

professionally. Certainly the examples in this tutorial are simple, but they illustratemost of the servlet concepts you would use to create a Web application. There aremore features (configuration and otherwise) available to you, but the core of almostevery Web app written with the Java language is one or more servlets acting asgatekeepers for business logic on one or more servers behind the scenes.

More importantly, you've learned some techniques for using servlets well. Webapplications often grow into messy piles of code. By using some simple techniquesdriven by fundamental OOP principles, you can avoid the mess, and create appsthat are a joy to enhance and maintain.

ibm.com/developerWorks developerWorks®  

Introduction to Java Servlet technology © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 41

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 40/41

Resources

Learn

• David Geary's Advanced JavaServer Page s (Pearson Higher Education, 2001)

is a must-read.• If your Web application is too complex for simple JSP components, you may

wish to investigate the Velocity Template Engine or the Struts Web ApplicationFramework. Both projects are hosted by the Apache Foundation.

• The Java Technology home page is the "official" Java language resource. TheJava Servlet Technology section of the site offers a wealth of information onprogramming with servlets.

• The Java tutorial from Sun is an excellent resource. There is a "trail" forservlets.

• The developerWorks New to Java technology page is a clearinghouse fordeveloperWorks resources for beginning Java developers, including links totutorials and certification resources.

• Bruce Eckle speculates on historical reasons why many Web programmers arereluctant to override service().

• You'll find articles about every aspect of Java programming in thedeveloperWorks Java technology zone.

• Also see the Java technology zone tutorials page for a complete listing of freeJava-focused tutorials from developerWorks.

Get products and technologies

• Download the contacts.jar that accompanies this tutorial.

• Download Tomcat from the Apache Jakarta Project.

• You'll also need the Tomcat plug-in for Eclipse from Sysdeo. Once you'veinstalled it, check out the HelloWorld servlet setup "tutorial" from Sysdeo.

Discuss

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Roy W. Miller

Roy Miller is an independent software development coach, programmer, and author.

developerWorks® ibm.com/developerWorks

Introduction to Java Servlet technologyPage 40 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

8/7/2019 Intro Servlets

http://slidepdf.com/reader/full/intro-servlets 41/41

He began his career at Andersen Consulting (now Accenture), and most recentlyspent three years using Java professionally at RoleModel Software, Inc. in HollySprings, NC. He has developed software, managed teams, and coached otherprogrammers at clients ranging from two-person start-ups to Fortune 50 companies.

ibm.com/developerWorks developerWorks®