Introduction to Servlets

Guest Posts joeabala

INTRODUCTION TO SERVLETS


A Servlet is basically a Java Program that executes within a Web server or an Application Server, acting as a middle layer between requests sent from a web client and a database on the HTTP server. By use of Servlets, you can dynamically come up with web pages, obtain information from users through web forms and display records from a database.

With that in mind, a Servlet is a Java class that complies to the Java Servlet API. This API is the standard for executing Java classes that respond to requests. Javax.servlet.http is a package that specifies HTTP specific subclasses for the communication of the Servlet and the Servlet container. Therefore, you can use a Servlet to establish dynamic content to a web server through the Java platform. The dynamic content generated is usually HTML but it may be in other forms such as XML. Servlets can also be used to maintain state in session variable through the use of HTTP cookies or URL rewriting. Servlets are usually packaged in a WAR file.

WEB / SERVLET CONTAINER


A web container/ Servlet container is used when it comes to deployment and Servlet execution. A Servlet container is basically the component of a web server that communicates with a Servlet. It does this by keeping track of the Servlet’s lifecycle,  Servlet url mapping and making sure that the URL requester contains the required access rights. Example of web containers include GlassFish server from Oracle and Apache Tomcat.

ADVANTAGE OF SERVLETS


The advantage of using Servlets is that they are more powerful and easy to use as compared to Traditional CGI scripts (Common Gateway Interface). Servlets are also platform independent since they are written in java and they are famous for their fast performance.

SERVLET LIFE CYCLE


Below is the life-cycle of a Servlet :-

  1. The first cycle is the construction and initialization of the Servlet. This is done by the init method which passes an object that implements the javax.servlet.ServletConfig interface. This object grants the Servlet access to the name-value initialization parameters from the corresponding application.

  2. The Servlet then handles any calls from the client to the service method. Each request is given a separate thread for this process. The service method checks the requests and diverts them to the appropriate method.

  3. Finally the Servlet is removed from service. The Servlet container calls the destroy method. This method, like the init method, is called only once throughout the Servlet lifecycle.


GETTING STARTED


Assuming that you have the required tools (JRE/JDK and Tomcat/GlassFish server) installed to compile and run a Servlet,  let’s start with baby-step codes. To create a Servlet we must extend the HttpServlet class with the doGet and doPost methods. As we noted earlier, HttpServlet  is an abstract class that is extended whenever we want to communicate through the HTTP protocol.

By convection, method doGet is used for static contents ie when we do not want to alter our data. doPost is used for dynamic content ie for creating and updating data hence alteration of data. Method doPost is more secure than doGet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {
  
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  }

}





The above example is the basic structure of a Servlet class. It does not output anything.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {
  
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    /*
setContentType("text/html") is the type of response you want to send
to the client.In our case its html.
*/

    response.setContentType("text/html");

/*
Obtain a PrintWriter object for writing to character streams.
It enables us to send character text to the client.
*/
    PrintWriter writer = response.getWriter();
    private String message = "Welcome to Servlets!";

    
    writer.println("");
    writer.println("");
    writer.println("

" + message + "

"); writer.println(""); writer.println(""); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }




The above code will output our message; Welcome to Servlets. Read the comments for further explanation.

This is the introduction to Servlets, basic web page output.