How to manually create a Java servlet

Home > Search > How-to

A servlet is run from an application server such as Tomcat or WebSphere. In this tutorial, we will create a servlet on Tomcat. If you do not have a Tomcat application server setup, follow the instruction in the tutorial on how to install Tomcat.

Create the following directories:

  • $tomcat_home/webapps/myApp/src
  • $tomcat_home/webapps/myApp/WEB-INF/classes


In the $tomcat_home/webapps/myApp directory, create a file named index.html, and add the following markup to the index.html file.

<a href="myServlet">Click here</a> to test your servlet.


Assuming Tomcat is listening on port 8080, you should now be able to navigate to, and view the index.html page you just created. Next we will create the Java servlet.


In the $tomcat_home/webapps/myApp/src directory, create a file named, and add the following markup to file.

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.util.*;

public class myServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  out.println("Hello World. If you are seeing this text, the servlet is working.");


Use the javac command to complie into myServlet.class. The -d option is the path to where myServlet.class file will be created. If you are unsure where servlet-api.jar is located, use the find command (find $tomcat_home -iname "servlet-api.jar").

~]# javac 
-classpath '/path/to/servlet-api.jar' 
-d $tomcat_home/webapps/myApp/WEB-INF/classes 


In the $tomcat_home/webapps/myApp/WEB-INF directory, create a file named web.xml, and add the following markup to web.xml file.

<?xml version="1.0" encoding="UTF-8"?>





You should now be able to navigate to, and the text from the myServlet.class file will be displayed.

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.