Developing a simple Hello World servlet

In this tutorial you will learn how to develop a simple servlet. Here we start with some step by step to develop servlet.

• Create the web application directory structure and you can create the src folder any where you want.

• Write a public class HelloServlet by making the subclass javax.servlet.http.HttpServlet class. javax.servlet.http.HttpServlet is the class which is in servlet-api.jar. so if you to qulify a class as servlet, that class should be extends by javax.servlet.http.HttpServlet.

• There is service() method in javax.servlet.http.HttpServlet. You have to override the service() method in your servlet class.

• Whatever you have suppose to do, keep inside the service method, so implement your business inside service() method.

• Open a writer to send the output to the browser.

• Use writer to send output back to browser.

• Close the write. Finally the servlet class looks like

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 * Servlet implementation class HelloServlet
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     * @see HttpServlet#HttpServlet()
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.print("Say hello to eveybody");

• We have to create the classes folder inside WEB-INF folder. It is mandatory, compile the HelloServlet class and put into the classes folder.

• Register the servlet in deployment descriptor(web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
    xsi:schemaLocation="" id="WebApp_ID" version="2.5">

Deploy the hello-app application into tomcat

Make a war file of web application hello-app and copy into webapps folder of tomcat. Restart the tomcat and you can access HelloServlet by this url.


The browser should give the output as in your browser.

“Say hello to everybody”