Java Servlet Explanation and Example


In this article, we explain what is a Servlet and show you a simple Servlet Example. Servlets run on a web server and are used to create dynamic webpages.

servlet component diagram

Why do we need servlets?

With the help of servlets we can fetch the html form data. If my client wants to interact with the database, web service or other application then they need some middle layer which can transform the data into a suitable form for web browsers. Servlet act as a middle layer.

Servlet is a java class that is used to handle the http requests. Data from a html form can be send using GET, POST or other methods. Mainly we user either GET or POST.

To create a servlet you need to create a base class of HttpServlet class. Inside the base class of HttpServlet we can define the methods to handle the GET and POST request.

public class HelloServlet extends HttpServlet{
}

Servlet Example

We are going to implement our own servlet to generate a html output.

  1. To create a servlet you need to extend HttpServlet class.
    public class welcome extends HttpServlet {
    }
    
  2. Packages named javax.servlet and javax.servlet.http provides classes and interfaces to develop a servlet.
  3. Most of the time our servlet deals with two type of requests. First is GET and second is POST.
  4. Our servlet handles GET request using the doGet() method.
     @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
           // your logic here
        }
  5. Our servlet handles POST request using the doGet() method.
    @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
           // your logic here
        }

HttpServletRequest and HttpServletResponse

Both doGet() and doPost() take two arguments:

  • HttpServletRequest.
  • HttpServletResponse.

Request helps us to access the data from client. It can be the form data or HTTP request header.

Response helps us to specify the status codes and headers. We can set the content type of our response with the help of HttpServletResponse.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author rajat
 */
@WebServlet(urlPatterns = {"/welcome"})
public class welcome extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Welcome to kb4dev</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Welcome to kb4dev.com </h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

Explanation of processRequest() method

  • We have implemented a processRequest() method which helps us to handle both GET and POST request.
  • response.setContentType() helps to specify that our response is html.
  • PrintWriter object is used to send charater text to client by using println() method.

Output