Servlet technology

What is a Servlet?

Servlet can be described in many ways, depending on the context..

  • Servlet is a technology which is used to create a web application.
  • Servlet is an API that provides many interfaces and classes including documentation.
  • Servlet is an interface that must be implemented for creating any Servlet.
  • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
  • Servlet is a web component that is deployed on the server to create a dynamic web page.

What is a Servlet Container?

In Java, Servlet container generates dynamic web pages. So servlet container is the essential part of the web server that interacts with the java servlets. Servlet Container communicates between client Browsers and the servlets..

A client browser accesses a Web server or HTTP server for a page.

  • The Web server redirects the request to the servlet container (Servlets are HTTP listeners that run inside the servlet container).
  • The servlet container redirects the request to the appropriate servlet.
  • The servlet is dynamically retrieved and loaded into the address space of the container, if it is not in the container.
  • The servlet container invokes servlet init () method once when the servlet is loaded first time for initialization.
  • The servlet container invokes the service () methods of the servlet to process the HTTP request, i.e., read data in the request and formulate a response. The servlet remains in the container's address space and can process other HTTP requests.
  • Web servlet generates data (HTML page, picture ...) return the dynamically generated results to the correct location.

Servlet Life Cycle

Servlet can have Life Cycle

  1. Loading Servlet Class: A Servlet class is loaded when first request for the servlet is received by the Web Container.
  2. Servlet instance creation: After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only once in the life cycle.
  3. Call to the init() method: init() method is called by the Web Container on servlet instance to initialize the servlet.
  4. Call to the service() method: The containers call the service() method each time the request for servlet is received. The service() method will then call the doGet() or doPost() methods based on the type of the HTTP request, as explained in previous lessons.
  5. Call to destroy() method: The Web Container call the destroy() method before removing servlet instance, giving it a chance for cleanup activity.

Simple Servlet example

import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
   private String message;

   public void init() throws ServletException {
      responseMessage = "Hello World";

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      // Set response content type

      PrintWriter out = response.getWriter();

   public void destroy() {
      // do nothing.


Our exampe from gitlab

 git clone

How to run

javac -classpath G:\Lesson\webproject\web\lib\servlet-api.jar -d G:\Lesson\webproject\web\WEB-INF\classes

Servlets - Writing Filters

  1. To intercept requests from a client before they access a resource at back end.
  2. To manipulate responses from server before they are sent back to the client.

Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor.

example from




When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

package am.developer.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * Created by User on 4/20/2019.
public class FilterServlet implements Filter {

    public void init(FilterConfig fc) throws ServletException {}

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        PrintWriter out = servletResponse.getWriter();
        String pass = servletRequest.getParameter("pass");
            filterChain.doFilter(servletRequest, servletResponse);
            out.println("You have enter a wrong password");
            RequestDispatcher rs = servletRequest.getRequestDispatcher("index.html");
            rs.include(servletRequest, servletResponse);
    public void destroy() { }


Servlets - Cookies Handling

Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.

There are three steps involved in identifying returning users

  1. Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  2. Browser stores this information on local machine for future use.
  3. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

Setting Cookies with Servlet

Cookie cookie = new Cookie("key","value");
Setting the maximum age
cookie.setMaxAge(60 * 60 * 24);
Sending the Cookie into the HTTP response headers

Servlets - Session Tracking

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

There are 3 way to keep any record of previous client request

  1. CookiesA webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
    This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.
  2. Hidden Form Fields A web server can send a hidden HTML form field along with a unique session ID as follows
    <input type = "hidden" name = "sessionid" value = "12345">
    This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.
    This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking
  3. The HttpSession Object

The HttpSession Object

servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.

HttpSession session = request.getSession();
package am.developer.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecondServlet extends HttpServlet {

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

        // Create a session object if it is already not  created.
        HttpSession session = request.getSession(true);
		if (session.isNew()) {
			session.setAttribute("key", "value");
		} else {




Servlets - Http Status Codes

Most using Http request Status Codes

  1. 200 OKThe request is OK
  2. 201 CreatedThe request is complete, and a new resource is created
  3. 400 Bad RequestThe server did not understand the request
  4. 401 UnauthorizedThe requested page needs a username and a password
  5. 403 ForbiddenAccess is forbidden to the requested page
  6. 404 Not FoundThe server cannot find the requested page
  7. 500 Internal Server ErrorThe request was not completed. The server met an unexpected condition.
  8. 503 Service UnavailableThe request was not completed. The server is temporarily overloading or down.

Servlets - Page Redirection

Page redirection is a technique where the client is sent to a new location other than requested. Page redirection is generally used when a document moves to a new location or may be because of load balancing.

package am.developer.servlet;
		public class ServletPageRedirect extends HttpServlet {
			public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {

				// Set content type

				// New location to be redirected
				String page = new String("");
				response.setHeader("Location", page);    

Servlets - Annotations

The annotation types introduced in Servlet 3.0

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

public class MoodServlet extends HttpServlet {

In this case no need define servlet in the web.xml

Filter servlet - Annotations

The annotation types introduced in Servlet 3.0

import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(filterName = "TimeOfDayFilter",
urlPatterns = {"/*"},
initParams = {
    @WebInitParam(name = "mood", value = "awake")})
public class TimeOfDayFilter implements Filter {

The @WebInitParam annotation is used for specifying an initialization parameter for a Servlet or a Filter. getInitParameter("test-param");

In this case no need define servlet in the web.xml

RequestDispatcher in Servlet

The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface

  1. public void forward(ServletRequest request,ServletResponse response) throws ServletException,
    Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
  2. public void include(ServletRequest request,ServletResponse response)throws ServletException,
    Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

Good example Forward and Include using when we create login

public class FirstServlet extends HttpServlet {  
	public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
		PrintWriter out = response.getWriter();  
		String username = request.getParameter("username");
		String userpass = request.getParameter("userpass");  
		if(LoginUtils.validate(username, userpass)){  
			RequestDispatcher rd=request.getRequestDispatcher("servletWelcomePage");  
			out.print("Sorry password or username is not valid!");  
			RequestDispatcher rd = request.getRequestDispatcher("index.html");