Back to Thoughts On Technology Page | Back to Peter's Home Page | Back to Family Home Page



Simple Java Servlet with JSP Example
Peter Rose - 12/2009


Abstract

Summary

Download and Install Resources

Building The Application Framework

Testing Tomcat

Building The Welcome JSP Page

Building The Servlet

Adding AbstractCatBaseAction

Enabling Servlet To Display JSP

Communicating From The Browser To The Servlet

The Complete Servlet





Abstract
Demonstrate the most basic steps in order to get an Apache Tomcat web application up and running.


Summary
Most times when we as software developers go into a job, there is a pre built infrastructure in place. Many times, this structure is built around some third party framework, such as Apache Struts, or WebSphere, or whatever. So, we just look at the recipe that's laid out for us and we jump in.

But when was the last time you have actually had to start from scratch and build a web app? Kids just out of college can probably do it, but those of us who have just been writing apps for a living most likely would be stumped. I was and so I decided to try it. Actually, I tried it three times in the last 5 years and each time it took me over a week of study and trial and error mucking around to get something going.

How tough should this be, and why is there no simple explanation out there on the web? Well, there are a lot of explanations and examples. But each one of them uses some kind of third party tool, like Eclipse, that hides some critical piece of the puzzle so that if you're on JBuilder, for example, the layout logic of files or whatever just don't translate into something you can understand and apply to your own environment.

So I'm going to do this the brute force way so you can see how the pieces fit together. Will you ever be faced with this level of concern? Probably not. But if you get this, then you get all the other stuff because it's all built on some very simple basic concepts.

All I'm going to use in this example is a plain text editor, and Apache Tomcat for the web server. That's it. Well, I'll use Apache Ant scripts to do the build and creation of a war file which is the most confusing part of it and not really relevant to building the app itself. Most IDE's contain this functionality, and quite frankly, I'm in no mood to teach Ant.

Suffice it to say, everything depends on being able to build and deploy a war file into the Tomcat container. But there is a way around this, and I'll show you how when we get to that part. But I'm not going to spend a whole lot of time clouding the central issues here.

The web app that I will be building is called Catalog. It's purpose is to store a listing of books. Pretty simple. Here we go....


Download and Install Resources
So, there's some 'stuff' you need to make all of this happen. I don't know when you will be reading this document so I'm not going to give references. Just download the stuff and then I'll show you where to put things.

Stuff You Need

  • Apache Tomcat
  • Java JDK
  • Apache Ant
  • Some kind of text editor - even Windows Notepad if you have no clue...

Create App Directory Structure
You will need to create two directory structures on your file system: one for development tools and the other for the application.

I created a directory zdev to store all of my development tools, i.e. tommycat, java, ant, etc. When I did this article, for example, I downloaded Apache Tomcat file apache-tomcat-6.0.20. So that directory structure sits under zdev.

My applications directory is as follows:


pmr
  catalog
    ant
    archives
    bin
    build
    compilelib
    src
      com
        pmr
          cat
            beans
            controller
            service
    war
      catalog
        cat
        css
        META-INF
        WEB-INF
          classes
          lib
  deploy
    war




Building The Application Framework
Okay, we've got the basic structure of our application set up. We've got all the tools we need spun out into the zdev directory, and we've built the directory structure our application will be developed in.

Breaking Down The App Directory Structure
As intimidating as all that directory structure looks, each directory (other than the obvious src and war directories) has a purpose in ending up with a web application. Let's go through each one as to what's in there. This is the step you're going to do after you download and install the 'stuff' and have created the above application directory structure.

  • ant: This is where all of your utility programs go to make building and deploying your war file simple. Since I'm not teaching any of this stuff, I'll just include the files in an appendix. If you're familiar with this stuff, you can easily map all of it to your application. If you have no clue about any of this, don't dispair. I'll show you how to fade all of this later, though not in much depth. It's all a hack so you'll be on your own as it's really only specific to tommycat. Anyway, the files you will find in here are as follows: cat.xml, catbuild.xml, custom.properties, setenv.bat, tomstart.bat, and tomstop.bat
  • archives: This is used by Ant and the build scripts cat.xml and catbuild.bat to store the catalog.jar and catalog.war files which are then swept up into tommycat. You'll see it's use in cat.xml, which is the build file for this project.
  • build: This is used by Ant and the build scripts cat.xml and catbuild.bat to create the com.pmr.cat directory structure containing the Java .class files and the jsp directory structure to hold all of the war directories .jsp files, i.e. war/catalog/cat.
  • compilelib: This is the application specific lib directory. Because our app is pretty simple, we really don't need any external .jar files to reference. Our CLASSPATH setting and our build file take care of grouping any .jar files we need into the war file. For example, because our app will use servlets, we're going to specifically need both the jsp-api.jar and servlet-api.jar files. I could download these from somewhere and stuff them into this directory, but instead I choose in my build file to use the ones in tommycat's lib directory. Don't worry about this stuff. When you go to compile your code or fire up tommycat, if something is missing, you'll know right away.
  • war/catalog/cat: This is where we will put our welcome.jsp file.
  • war/catalog/css: This is where we will put our catalog.css file.
  • war/META-INF: The file context.xml is a file that tells tommycat what context this application will be referenced by. It looks like this
        <Context path="/catalog"
            docBase="catalog"
            reloadable="true"
            userNameing="false"
            privileged="true"
            debug="0"
            swallowOutput="false"/>
        
  • war/catalog/WEB-INF: This is where the web.xml file that we'll need to build will go. Create the following web.xml file and stick it into there:
        <?xml version="1.0" encoding="ISO-8859-1"?>
        <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
            //DTD Web Application 2.3//EN"
            "http://java.sun.com/dtd/web-app_2_3.dtd">
    
        <web-app>
            <display-name>Catalog Application</display-name>
            <description>Catalog Application</description>
    
            <servlet>
                <servlet-name>cat</servlet-name>
                <servlet-class>com.pmr.cat.controller.CatAction</servlet-class>
            </servlet>
    
            <servlet-mapping>
                <servlet-name>cat</servlet-name>
                <url-pattern>/cat</url-pattern>
            </servlet-mapping>
        </web-app>
        

Let's take a closer look at the guts of some of the files listed above.

ant
As I mentioned, there are a bunch of helpful files here in the ant directory. I'm going to list the content of each one mostly so you can see where the Java and jsp files you create are going to end up in tommycat, or in their corresponding locations in whatever webserver you are using.

setenv.bat

set ANT_HOME=\zdev\apache-ant-1.7.1
set CATALINA_HOME=\zdev\apache-tomcat-6.0.20
set JAVA_HOME=\zdev\Java\jdk1.6.0_17
set CATALINA_BASE=\zdev\apache-tomcat-6.0.20
set PATH=%PATH%;\zdev\apache-ant-1.7.1\bin
set CLASSPATH=%CLASSPATH%

Any build file or process that you use is going to need to know where the webserver is, where Ant itself sits (if you choose to use it), and what other objects are needed in the Java classpath. For example, at work I had to develop a web service client and we used Apache Axis to generate the objects in the .wsdl file from the web service server. All of these Axis files had to be referenced in the Java classpath.

custom.properties

tomcat.deploy.home=\\zdev\\apache-tomcat-6.0.20
tomcat.home=\\zdev\\apache-tomcat-6.0.20
dir.deploy=${tomcat.deploy.home}\\webapps
javaexec=\\zdev\\Java\\jdk1.6.0_17\\bin\\javac
javac.compiler=javac1.6

The custom.properties file is used by the application ant build file, cat.xml.

tomstart.bat, and tomstop.bat

\zdev\apache-tomcat-6.0.20\bin\startup.bat
and
\zdev\apache-tomcat-6.0.20\bin\shutdown.bat

These files will start and stop your local tommycat.

catbuild.xml

ant -f cat.xml deploy

This is the file you use to build and deploy your application. Notice that it references the build file cat.xml and the specific ant target action of 'deploy'. See cat.xml.

cat.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="main" default="init">
    <property environment="env"/>
    <property file="custom.properties"/>
    <property name="projectname" value="catalog"/>
    <property name="dir.root" value="../"/>
    <property name="build.compiler" value="${javac.compiler}"/>
    <property name="dir.lib" value="${dir.root}/compilelib"/>
    <property name="dir.src" value="${dir.root}/src"/>
    <!--property name="dir.utils.src" value="${dir.root}/../utils/src"/-->
    <property name="dir.archives" value="${dir.root}/archives"/>
    <property name="dir.build" value="${dir.root}/build"/>
    <property name="dir.deploy" value="${tomcat.home}/webapps"/>
    <property name="javac" value="${javaexec}"/>
    <property name="dir.warbase" value="${dir.root}/war"/>
    <property name="warfilename" value="${projectname}.war"/>
    <property name="warcontext" value="${projectname}"/>
    <property name="dir.jdk" value="${env.JAVA_HOME}/jre/lib"/>


    <target name="init">
        <echo message="${projectname}"/>
        <echo message="${build.compiler}"/>
        <echo message="${build.compiler.fulldepend}"/>
        <echo message="${compileWithDebug}"/>
        <echo message="${dir.root}"/>
        <echo message="${dir.src}"/>
        <!--echo message="${dir.utils.src}"/-->
        <echo message="${dir.archives}"/>
        <echo message="${dir.build}"/>
        <echo message="${dir.lib}"/>
        <echo message="${dir.deploy}"/>
        <echo message="${dir.jdk}"/>
        <echo message="${javac}"/>
        <echo message="${dir.warbase}"/>
        <echo message="${warfilename}"/>
        <echo message="${warcontext}"/>
    </target>


    <target name="prepare" depends="init">
        <mkdir dir="${dir.archives}"/>
        <mkdir dir="${dir.build}"/>
    </target>


    <target name="reset">
        <antcall target="prepare"/>
    </target>


    <path id="project.classpath">
        <pathelement location="${dir.src}"/>
        <fileset dir="${tomcat.home}/lib">
            <include name="jsp-api.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/lib">
            <include name="servlet-api.jar"/>
        </fileset>
        <fileset dir="${dir.lib}">
            <include name="*.jar"/>
        </fileset>
    </path>


    <target name="build_cat">
            <delete file="${dir.archives}/${projectname}.jar"/>
            <javac srcdir="${dir.src}"
                includes="com/pmr/cat/**/*.*"
                destdir="${dir.build}"
                fork="yes"
                executable="${javaexec}"
                compiler="${build.compiler}"
                deprecation="off">
            <classpath refid="project.classpath"/>
            </javac>
        <antcall target="jar_cat"/>
    </target>


    <target name="build_war" depends="reset">
        <delete file="${dir.archives}/${warfilename}"/>
        <antcall target="build_cat"/>
        <copy todir="${dir.build}/jsp/${projectname}">
            <fileset dir="${dir.warbase}/${projectname}"
            includes="**/*.jsp"/>
        </copy>
        <touch>
            <fileset dir="${dir.build}/jsp/${projectname}"/>
        </touch>
        <war    destfile="${dir.archives}/${warfilename}"
                webxml="${dir.warbase}/${projectname}/WEB-INF/web.xml"
                basedir="${dir.warbase}/${projectname}"
                excludes="**/web.xml"
                includes="${projectname}/**/*.*,**/*.jsp,css/*.css,
                WEB-INF/lib/*.*,WEB-INF/*.*,
                WEB-INF/classes/resources/*.*,
                WEB-INF/classes/**/*.class,META-INF/context.xml">
            <lib dir="${dir.lib}"
                includes="*.jar"/>
            <lib dir="${dir.archives}"
                includes="${projectname}.jar"/>
        </war>
        <!--
            COPY THE WAR TO ARCHIVES
        -->
        <copy todir="${dir.root}/../deploy/war">
            <fileset dir="${dir.archives}"
            includes="${warfilename}"/>
        </copy>
    </target>


    <target name="jar_cat">
        <jar jarfile="${dir.archives}/${projectname}.jar"
            basedir="${dir.build}"
            includes="com/pmr/cat/**/*.class"/>
    </target>


    <target name="deploy" depends="build_war">
        <unwar src="${dir.archives}/${warfilename}"
            dest="${dir.deploy}/${warcontext}"/>
    </target>
</project>

The key here is to go to the target 'deploy' which is what's in the catbuild.bat command file and follow the bouncing ball through this cat.xml build file as to how the files are being compiled and where they are going. Of note is that this build file does not pre-compile the .jsp files. It just moves them up into tommycat's webapps. When the application calls one of these .jsp files, tommycat will compile it and move the resulting class file to where it needs to go.

Also note that I have named this file cat.xml. It should really be called build.xml. And, in fact, if it isn't called that in most containers, the webserver will have no idea what to do with the file. I named this cat.xml so that it is clear that we are not using some third party framework and that you will know exactly which file I am talking about when I reference cat.xml as there are so many possible build.xml files that float around in a web app that it can get you really confused. It did me. But then, maybe this will confuse you even more. I dunno. All I can do is try to make a clear distinction as to which file I am using. Just know that in the 'real world' you should name this thing build.xml.


Testing Tomcat
Before going any further, we need to test this framework for basic functionality. This first test will be to just see if we have tommycat running correctly.

I have a little batch file gocat.bat in my Windows classpath that takes me to the ant directory and executes the setenv.bat file to get my environment all set.

c:
cd C:\pmr\catalog\ant
setenv

Open a dos command window and type gocat at the prompt. It should leave you in the ant directory where you can now type: tomstart. If all is well, another dos window should pop up with tommycat humming away. If you get any errors, you have to fix them now or you'll never get the app running.

Now, open a browser and type http://localhost:8080/. If you get a welcome screen that proclaims 'If you're seeing this page via a web browser, it means you've setup Tomcat successfully. Congratulations!' then you are all hooked up and ready to start writing your application! If you don't get this message, you'll have to debug and fix.


Building The Welcome JSP Page
Our next objective is to see if tommycat can find a jsp that you write. Build the following file and put it into the war/catalog/cat directory:

welcome.jsp


<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<title>Catalog - Input</title>
</head>
<body>

<table>
    <tr>
        <th colspan="9">Catalog Application</th>
    </tr>
    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>
    <tr>
        <td colspan="9">
            <input type="submit" value="Add New Entry">
        </td>
    </tr>
    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>
</table>

</body>
</html>

Now, type the following into your browser:

http://localhost:8080/catalog/cat/welcome.jsp.

BOOM! You should get a 'HTTP Status 404 - /catalog/cat/welcome.jsp' error.

Why? Well, how is tommycat supposed to know where this file is? But, you plead, isn't that what the url is telling tommycat to do, to look in 'catalog/cat' for the welcome.jsp. Ahhhh... yes, it does. But - and here's what escapes most people at first - tommycat is referencing it's catalog/cat directory.

Hummmm... take a look in the tommycat directory structure under the webapps directory where your catalog application should be, you don't see anything. Why not? Because you didn't put any files there or build a war file that was then deployed into the tommycat's directory structure.

So, now what? Well, let's brute force things just a little here as this will be really instructive for where the cat.xml build file is going to be dropping files. Stop tommycat and then under tommycat's webapps directory, create catalog/cat and stuff welcome.jsp in there. Now, restart tommycat and hit the same url. Now you should get the page to display. Smooth...

What we just did was to fade the building and deploying of the war file. To continue along this line would be really silly as things can get really complicated - as evidenced by all that's going on in the cat.xml build file.


Building The Servlet
Next on the agenda is to build a Java servlet and see if we can hit it from the browser. What does that mean? Well, like we typed into the browser a direct hit on the welcome.jsp via

http://localhost:8080/catalog/cat/welcome.jsp

we now want to see if we can type into the browser something like the following

http://localhost:8080/catalog/cat

and have that request go to a servlet we will write called CatAction.java and have that servlet respond with a message to the browser of:

'You have reached CatAction.doGet()'

By doing this, we will prove out that not only is tommycat running, but that the important file web.xml that holds everything together is doing it's thing correctly.

One note on me calling this servlet 'CatAction'. The term 'Action' is pretty specific to applications that are running Apache Struts framework because all servlets extend from the Struts base Action.java class. I could call my servlet 'CatServlet.java' or 'CatController.java' or even 'Bob.java' and it wouldn't make a bit of difference.

Note in the following duplication of the web.xml the <servlet> and <servlet-mapping> tags.

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
        //DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

    <web-app>
        <display-name>Catalog Application</display-name>
        <description>Catalog Application</description>

        <servlet>
            <servlet-name>cat</servlet-name>
            <servlet-class>com.pmr.cat.controller.CatAction</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>cat</servlet-name>
            <url-pattern>/cat</url-pattern>
        </servlet-mapping>
    </web-app>
    

What these tags are telling tommycat to do is to direct any url request of catalog/cat to the CatAction.java servlet. In webapps, such requests are either a 'GET' or a 'POST'. Thus, we can test this connectivity directly from the browser. All we need to do is build the servlet and then use the ant build process to deploy the application. Here's the servlet:

CatAction.java


package com.pmr.cat.controller;

import java.io.IOException;
import java.io.PrintWriter;

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

public class CatAction extends HttpServlet {
    public void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
                throws ServletException, IOException {
        System.out.println("You have reached CatAction.doGet()");
        PrintWriter out = response.getWriter();
        out.println("You have reached CatAction.doGet()");
    }
}

If you have built all of the files mentioned in this article, then just go to the dos window that you issued your 'tomstart' command and type in 'catbuild'. You'll see a flury of activity with ant telling you that the build was successful and there will be messages about the war file being built and deployed. If you don't get this, then I'm sorry, but something baaaaaad has happened, and you're just going to have to figure it out - as there are a lot of things that can go wrong and are far beyond the scope of this little article and my patience.

Once you get a successful build, go to the browser and type in

http://localhost:8080/catalog/cat

And it's a wonderful thing when 'You have reached CatAction.doGet()' shows up in the browser as well as in the tommycat window. Life is good.

Note that you may have to hit the refresh button on the browser while holding the shift key every time you rebuild as you are not recompiling the jsps; just dropping new text onto tommycat so you sort of have to force it along at this point.


Adding AbstractCatBaseAction
I'm sure you know enough about the HTTP protocol to know that there is a 'GET' and a 'POST' method. Usually in apps, you create an abstract class that delegates to an abstract method like 'processRequest()' which is then implemented in the concrete class. So, that's the next step and thus we'll be looking to call the 'processRequest()' method on this central traffic cop concrete servlet/action class CatAction which will now extend AbstractCatBaseAction.java.


Enabling Servlet To Display JSP
Okay, so now we can type into the browser the name of the jsp and see that, and we can type in the reference to the servlet and we see that we are talking to the servlet. Next is to call the servlet from the browser and have it display the jsp for us. All that takes is adding a couple of lines of code to the processRequest() method of the servlet:


    public void processRequest(
            HttpServletRequest request,
            HttpServletResponse response)
                throws ServletException, IOException {
        System.out.println("You have reached CatAction.processRequest()");
        PrintWriter out = response.getWriter();
        out.println("You have reached CatAction.processRequest()");

        String forwardTo = "/cat/welcome.jsp";
        RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher(forwardTo);
        dispatcher.forward(request,response);
    }




Communicating From The Browser To The Servlet
So, right now, we've got a web app that a client can access and get a response from. This is how you get your initial page in front of the user. That's why we called it welcome.jsp. So, what next?

Well, let's say we are the library and we are allowing a user to access our website (catalog) to list a book title they have that they'd like to donate. We want them to be able to type in the name of a book and submit an html form that our CatAction servlet will receive and then store that book title on our database. We'd also like to jazz up the welcome.jsp interface a little with some .css magic. And, once we have stored the book in our database we want to be able to let the user know we got it and thank them for donating the book. Here's the full welcome.jsp that we're going to end up with:

welcome.jsp



<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<link href="<%= request.getContextPath()%>/css/catalog.css" rel="stylesheet" type="text/css">
<title>Catalog Application</title>
</head>
<body>
<script language="javascript1.2" type="text/javascript">

function submitRequest(toMethod) {
    document.forms[0].action.value=toMethod;
    document.forms[0].ptitle.value=document.getElementById("ptitleid").innerHTML;
    document.forms[0].pauthor.value=document.getElementById("pauthorid").innerHTML;
    document.forms[0].pcondition.value=document.getElementById("pconditionid").innerHTML;
    document.forms[0].submit();
}

</script>


<form method="GET">
<input type="hidden" name="action" value="">
<input type="hidden" name="ptitle" value="">
<input type="hidden" name="pauthor" value="">
<input type="hidden" name="pcondition" value="">

<table>
    <tr>
        <th colspan="9">Catalog Application</th>
    </tr>
    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>
    <tr>
        <td colspan="9">
            <input type="submit" value="Add New Entry" onClick="submitRequest('storeEntry')">
        </td>
    </tr>
    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>
    <tr>
        <th>Book Name</th>
        <th>Author</th>
        <th>Condition</th>
    </tr>
    <tr>
        <td><input type="text" id="ptitleid" name="title"></td>
        <td><input type="text" id="pauthorid" name="author"></td>
        <td><input type="text" id="pconditionid" name="condition"></td>
    </tr>
    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>

    <%
        String msg = (String)request.getAttribute("successMessage");
        if(msg != null) {
            %>
            <tr>
                <td colspan="9">
                    A special message for you -<br>
                    <%=msg%>
                </td>
            </tr>
    <% } else { %>
            <tr>
                <td colspan="9">
                    Please enter your donation above...
                </td>
            </tr>
    <% } %>

    <tr>
        <td colspan="9" style="background-color:white;"> </td>
    </tr>
</table>

</body>
</html>



And here's a little catalog.css file. I do this just to show where the file will end up in tommycat's webapps directory as well as how it's referenced on the page if you haven't done this type of thing before:

catalog.css


@CHARSET "ISO-8859-1";

table {
    width:900px;
}

th {
    background-color: blue;
    color: white;
}

td {
    font-size: 12px;
    font-weight: bold;
    text-align: left;
    background-color: #6F93B7;
    color: white;
}

Here are the key points in the new welcome.jsp file.

  • Hidden fields are used to transmit the properties to the servlet.
  • One of the hidden field properties, the action, is used to tell the servlet which internal method to call.
  • The parameter 'successMessage' is placed in the request scope by the servlet only when the internal method has stored the book.



The Complete Servlet
And here is the code for the complete code for the catalog servlet:

CatAction.java


package com.pmr.cat.controller;

import java.io.IOException;
import java.io.PrintWriter;

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

public class CatAction extends AbstractCatBaseServlet {


    public void processRequest(
            HttpServletRequest request,
            HttpServletResponse response)
                throws ServletException, IOException {
        System.out.println("You have reached CatAction.processRequest()");
        RequestDispatcher dispatcher = null;

        String action = (String)request.getParameter("action");
        System.out.println("  --action is: " + action);

        String forwardTo = "";
        if(action == null || action.trim().equals("")) {
            String msg = "No action CatAction.processRequest()";
            System.out.println(msg);
            forwardTo = "/cat/welcome.jsp";
       } else {
            String title = (String)request.getParameter("title");
            System.out.println("  --Title is: " + title);

            storeEntry(request, response);
            forwardTo = "/cat/welcome.jsp";
        }

        dispatcher = getServletContext().getRequestDispatcher(forwardTo);
        dispatcher.forward(request,response);
    }


    protected void storeEntry(
            HttpServletRequest request,
            HttpServletResponse response)
                throws ServletException, IOException {
        System.out.println("You have reached CatAction.storeEntry()");
        String successMessage = "Hey! Thanks for your donation!";
        request.setAttribute("successMessage", successMessage);
    }
}

Notice how the processRequest() method acts as a traffic cop to direct program control flow based on the value of the request parameter 'action'.

Just remember that a servlet's only job is to deal with the HttpRequest and no more. Once the request parameters have been pulled out and placed in a Map or Bean or used as method parameters, some other service class should be instantiated and called to do the actual work. For example, you would not make database access calls from the storeEntry() method on the servlet. You might instantiate a CatStoreEntryService object and pass it the parameters collected from the screen and an instantiated CatDAO. The service object is used to handle any business logic that needs to be done whereas the DAO would make the actual database call.



Back to Thoughts On Technology Page | Back to Peter's Home Page | Back to Family Home Page