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

package com.java.connect.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
 
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()
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.print("Say hello to eveybody");
        out.close();
    }
}

• 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="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>hello-app</display-name>
  <servlet>
    <description></description>
    <display-name>HelloServlet</display-name>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.java.connect.servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/HelloServlet</url-pattern>
  </servlet-mapping>
</web-app>

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.

http://localhost:8080/hello-app/HelloServlet

The browser should give the output as in your browser.

“Say hello to everybody”