First Servlet
In this session, we will create our first servlet. To keep things simple, it will just output “Hello, world” type string. In the following sections of the tutorial, we will dig deeper into servlet API.
First order of business is to add Servlet API dependency to our project's pom.xml. Add the following code snippet to pom.xml.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
Note the “provided” for scope. This means that servlet API will be provided by servlet container (Tomcat) at runtime. That way we avoid duplicating dependencies.
Servlet code
All servlets extends javax.servlet.http.HttpServlet class. This class provides methods to be overriden by subclasses to handle specific HTTP requests. Basically, the following methods can be overridden:
- doGet() - handles HTTP GET request
- doPost() - handles HTTP POST request
- doPut() - handles HTTP PUT request
- doDelete() - handles HTTP DELETE request
- init() - called when servlet is initialized
- destroy() - called when servlet is being removed, to free resources or perform cleanup
For our first servlet, we want to handle only HTTP GET requests, so we will override only doGet() method. Servlet code is shown bellow:
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_OK);
// print HTML content
resp.getWriter().print("<h1>Hello, Servlet!!</h1>");
// set content type to HTML
resp.setContentType("text/html");
resp.flushBuffer();
}
}
This is the simplest possible servlet which only prints “Hello, Servlet!” string to output stream. Here, we first set response status to HTTP 200 (OK) code, which indicates successful response. Then, we print HTML output using response writer object. This is similar to writing to standard out; we just need to keep HTML formatting and tags in check.
Finally, we set response content type to “text/html” and flush output buffer, which causes content to be actually written. Setting content type to “text/html” will indicate to browser that content should be displayed in HTML format. If nothing is set, it is assumed that content type is plain text.
Servlet Configuration
The final step in servlet development is to configure it for deployment in web.xml file. To do this, we need to add the following code to web.xml:
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.beyondrelational.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/helloservlet</url-pattern>
</servlet-mapping>
Tag “<servlet>” indicates servlet configuration section. Here, “<servlet-name>” defines unique name by which servlet is identified, while “<servlet-class>” defines actual Java class where servlet is defined.
Section “<servlet-mapping>” allows us to define URL that will map to a given servlet. Here, “<servlet-name>” is previously defined servlet name, and “<url-pattern>” is the browser URL that will invoke the servlet.
Note that URL patterns are defined relative to context path. In this case, it means that our servlet will be called when user enters the URL such as “http://localhost:8080/samplewebapp/helloservlet”.
The image bellow shows our servlet in a browser:

As you can see in this section, working with servlets is pretty straight forward and easy. However, you can also see one serious drawback of servlets. That is, we have to output HTML code using print() statements.
This is not so bad for simple HTML like in this example. But, for any serious application, this can be extremely tedious and error prone. Furthermore, HTML code gets mixed with Java code, which can make it a real hell to debug.
To address this issue, Java Server Pages were introduced. We will cover this topic in more depth in the following parts of this tutorial.
Find the sample web application here.