Getting started with Java Servlet API


Java servlet is one of the best technology for server side web application development. Java servlet and jsp are both very essential part if you are new to java web development. There are various new framework but at the base level they all use the servlet to do the work.

When we said servlet we mean the building block of new generation web development in Java. You all must be familiar with the Applets which ruled the world of WWW in late 1990s but there were so many limitations out there and the www was moving towards new generation. The web pages were moving from client side manipulation to server side advance CGI scripts. There were no place for static pages in the industry anymore. Java was again very quick to provide a great solution which comes out as Servlet.

The servlet is a server side technology and an API of Java EE specification which makes the building block. The servlet is a technique using which we generate dynamic web pages based on the response of what request server gets from users. This means we can write the code to create an interaction between the users and web server or better we say, with web applications.

With the servlet on job we can create web applications easily. We are going to show you how but before that we would like to cover up the basics on which stand servlet. Let us start from the advantages we get from servlets.

Advantages of servlets

Web Applications: Servlet is not just a HTML page generating technique, it is more than that. You can create a compleate web application using the servlets, where web application is a software created for web which works in two part. The business login part which is performed by servlets and user interface part is performed by HTML which is generated by servlet and other client side scripts like JavaScript etc.

Filters: Filters are abstract classes provided with the servlet API, these help to reduce the load off the servlet and can perform actions on request and response like authentication and response formatting.

Security: Servlet is in core term Java and uses JVM so all the security features of Java also applies here too.

Internationalization: Java Servlet provide you a mean of internationalize your web application just like you can do this with your Java softwares. You can create the servlets which may provide the response text in various known languages.

Multi threaded architecture: servlet life cycle is a three phase life cycle in which the most important phase works with the multi-threaded model and can serve multiple request in concurrency.

Well this is a few "why servlets are good" points on which you can build your requirement.

Let us now look at the life cycle of servlets, this is simple three phase life cycle as it shows in the Image below.

The Servlet Life Cycle

servlet life cycle

The life cycle is made up of three phases, init, service and destroy. Well there are new methods out ther doGet() and doPost() in latest specification and most of the people like to use them instead. But the service() is all right and you don't have to bother with the request type when you operate with the service() method. Now, let us look at the life cycle in more detail.

init: the init method is used to initialize the servlet, however its not necessary that you override this but well, it is helpful when you want to initialize some initial parameters, for example you want to create the database connection before you start processing any request which may contain database operation.

service: where initialization phase is optional and run once, the service method is a multi threaded method, initially the container load only one instance of the service and uses this to serve all the requests from the concurrent threads.

destroy: this is the last phase this phase act when the servlet is taken out from the container after the work is finished. So this clears up the resources.

It wont be much to take a lead on but let us look at the the servlet API. There is generic servlet which work on the basis of Servlet interface. But it was never a popular way, the web today is accessible using a very popular protocol HTTP, so java servlet provide the inbuilt support for HTTP protocol. We get a javax.servlet.http package which provide support for HTTP protocols. There is class HttpServlet and interfaces HttpRequest and HttpResponse.

There are methods in HttpServlet class which performs the task. Most used and common for the request processing are service or doGet and doPost. the init and destroy are the methods provided with the GenericServlet class which serves as the base class for HttpServlet. The following example will tell you about the basic structural example of servlet.


package home;

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;

public class HelloWorldServlet extends HttpServlet {
    PrintWriter out;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("Hello World");
        out.println("</body>");
        out.println("</html>");
	}
}

In the program we extend HttpServlet and override one of its method doGet, however we can replace it by service too, and it would not make much difference. In doGet, doPost or service we pass the HttpServletResponse and HttpServletRequest type reference as parameter. This is to let the service handle the http request and response.

there is an important file which defines the structure of the web application. This is called deployment descripter, and is placed in the folder named WEB-INF by the name of web.xml in this we need to register the servlet so that application could find it.


<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>HelloWorldServlet</servlet-name>
        <servlet-class>home.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/HelloWorldServlet</url-pattern>
    </servlet-mapping>
</web-app>

this is a general structure of the web application. We use servlet-tag to register servlet and servlet-name and servlet-class define the name value pair for the srevlet. We need to map a URL for this servlet which will be the calling url for the servlet.

when you deploy this application you will call this by using the url /HelloWorldServlet and following page would come up.

Demo Servlet

So this concludes this post. In this post we looked at the basics of servlet and servlet API also we saw how we create the servlet. I would suggest you to use the Netbeans IDE to work with servlet. This will give you excellent overview of the directory structure and also the hierarchy. It will make the most of it easier and also deployment would be much much easier. you will also get rid of compiling and deploying again and again manually.