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.
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,
- Write the Servlet
- Define your environment
- Compile the Servlet
- 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.
- 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.
- A Servlet is a Java class so let us begin by creating a new text document called
Simple.javain the 'src' subfolder of the WEB-INF folder.
- The Servlet begins by importing the packages required for the class:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
- Next we define our Servlet class as extending the HttpServlet class,
public class Simple extends HttpServlet { } - We will only be overriding 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:
HttpServletRequestandHttpServletResponseand raises two exceptions:ServletException, andIOException. - 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 theoutobject to which we will be writing our HTML.response.setContentType("text/html"); PrintWriter out = response.getWriter(); - 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"); - 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>"); - Finally we close the output stream,
out.close();
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.
- Create a batch file in the classes folder called set_env.bat.
- 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%
- Save and close this file.
- Open a command or DOS prompt and navigate to the 'src' directory, the one containing your
Servlet and this batch file.
- Execute the batch file by entering
set_env.batat the command prompt.
- 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.batnext time you open the command prompt.
Part 3. Compile the Servlet
- 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.classin 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("