JSP Course Topics

Workshop 9. Writing a Basic Servlet

Objective

The objective of this workshop is to create a simple Servlet that can respond to client requests and generate some output.

Time Available

This workshop should take no longer than 60 minutes.

Basic Servlet Workshop

Click the icon below to see a demo of the Servlet.

Demo

Okay so it is not very exciting but the request is passing a query string that defines a firstname and lastname parameters. You can see these in the address bar of your browser. The Servlet picks up these values and constructs the phrase "Hello Barney Bear". You can edit the URL in your address bar and change the values of 'Barney' and 'Bear' to something else and the Servlet will pick up these values.

There are four parts to this workshop and indeed in writing servlets. These are,

  1. Write the Servlet
  2. Define your environment
  3. Compile the Servlet
  4. Test the Servlet

Part 1. Write the Servlet

Application Servers can vary in the way they handle Servlets. This workshop assumes you are using Tomcat but if you are using a different Application Server then consult its documentation for details on deploying Servlets.

  1. First of all let us create a new web application with the appropriate folder structure. In Tomcat you'll find a webapps folder below the installation folder. In this folder create a new subfolder called 'testapp' and a subfolder of this called WEB-INF. Below WEB-INF create two subfolders 'classes' and 'src' and a xml file 'web.xml'. Your folder structure should be similar to the following.
    file system image
  2. A Servlet is a Java class so let us begin by createing a new text document called Simple.java in the 'src' subfolder of the WEB-INF folder.

  3. The Servlet begins by importing the packages required for the class:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    
  4. Next we define our Servlet class as extending the HttpServlet class,
    public class Simple extends HttpServlet
    {
    
    }
    
  5. We will only be overridding the doGet() method so add the following to the body of the Servlet,
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
                        throws ServletException, IOException
      {
    
    
      }
    

    Note, this method, as always, takes two parameters: HttpServletRequest and HttpServletResponse and raises two exceptions: ServletException, and IOException.

  6. The first thing we always do within the doGet() method is to define the content type for the output which is usually HTTP but could be other formats for example XML or even binary if the servlet is used to generate images. In our example we are outputting HTML and so we also instantiate the out object to which we will be writing our HTML.
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
  7. Next we want to analyse the query string and pick up the first and last names
    String sFirstName = request.getParameter("firstname");
    String sLastName = request.getParameter("lastname");
    
  8. And then it is just a matter of writing the appropriate HTML to the output stream
    out.println("<html>");
    out.println("<head>");
    out.println("<title>A Simple Servlet</title>");
    out.println("</head>");
    
    out.println("<body>");
    out.println("<h1>A Simple Servlet</h1>");
    
    out.println("<p>Hello " + sFirstName + " " + sLastName + "</p>");
    
    out.println("</body>");
    out.println("</html>");
    
  9. Finally we close the output stream,
    out.close();
    

By now your Servlet should look like this:

Download file icon

Part 2. Define the Environment

Before we can compile the Servlet we need to setup our environment specifically our classpath. A good practice is to create a batch file that will do this for you so in future you can just run this batch file to set your environment.

  1. Create a batch file in the classes folder called set_env.bat.

  2. In this file define your classpath to point to the JDK and to your Servlet Container. If you are using Tomcat the the example below would do. You may need to change the paths.
    rem JDK location
    Set jdk=C:\jdk1.3\bin
    
    rem JSP Container location
    Set AppServer_Home=[tomcat home]\common\lib
    Set servlet=%AppServer_Home%\servlet.jar
    
    Set CLASSPATH=%jdk%;%servlet%;
    
    echo %classpath%
    
  3. Save and close this file.

  4. Open a command or DOS prompt and navigate to the 'src' directory, the one containing your Servlet and this batch file.

  5. Execute the batch file by entering set_env.bat at the command prompt.

  6. You have now set the classpath correctly. Note, this classpath will only apply for the duration of the command prompt. If you close the window you will need to re-execute set_env.bat next time you open the command prompt.

Part 3. Compile the Servlet

  1. To compile the Servlet enter the following at the command prompt.
    javac -d ../classes Simple.java
    

    This will compile the Servlet and if it worked it will create the file Simple.class in the 'classes' folder, the '-d ../classes' switch tells the compiler where to put the compiled class file.

    If you encountered the error "javax.servlet does not exist" then your classpath is incorrect. Check the paths defined in your batch file and try again.

    Errors with the actual Servlet file are reported in the usual manner. Below is an error regarding a missing semicolon:

    Simple.java:33: ';' expected
        out.println("")
                       ^
    1 error
    

Here is a copy of the compiled Servlet:

Download file icon

Part 4. Test the Servlet

  1. We need to define each Servlet that you are intending to use in the web.xml file as follows.
    <?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>My Test Servlet</display-name>
      <description>My Test Servlet </description>
    
      <servlet>
        <servlet-name>SimpleServlet</servlet-name>
        <servlet-class>Simple</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>SimpleServlet</servlet-name>
        <url-pattern>/Simple</url-pattern>
      </servlet-mapping>
    <web-app>
    
  2. Since we made a change to the 'web.xml' file we will need to restart Tomcat before we can test our servlet
  3. To test the Servlet enter the following URL in a browser,

    http://localhost:8100/testapp/Simple?firstname=Barney&lastname=Bear

    Here the name of the web application is testapp. Next is the URL pattern that we defined in the 'web.xml' file '/Simple'. Finally we just have a normal query string starting at the question mark "?".

Advanced Servlets

The next section looks further at Servlets including working with sessions, JSP Actions and JavaBeans. More examples of Servlets can be found in Tomcat's examples.

Back Next