Java Servlet

Note: This tutorial is for developers who want to learn the concepts of java servlet.
This tutorial does not show you how to code. There are several examples online which will show you how to code.

Evolution

Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. CGI technology enables the web server to call an external program and delegate HTTP request to the external program to process the request.

  • For each request, it starts a new process
  • It uses platform dependent language e.g. C, C++, perl

Introduction

Servlet is a java object. It receives a request and generates response. There are many advantages of Servlet over CGI.

  • For each request new thread is created
  • Servlet uses java so it’s secure, platform independent, robust and no memory leaks since java takes care of garbage collection

All servlets must implement servlet interface, which defines lifecycle methods. javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. HttpServet class provides methods for handling HTTP-specific services.

Servlet lifecycle

Servlet container controls the lifecycle of servlet

When request is mapped to a servlet if an instance of a servlet does not exist, the web container

  • Loads the servlet class
  • Create an instance of the servlet class
  • Initializes the servlet instance by calling the "init" method
  • Invokes the "service" method, passing request and response objects
  • If it needs to remove the servlet, the container finalizes the servlet by calling the servlet's "destroy" method

ServletContext

ServletContext is an object created by web container to provide information to all the servlets. This object get information from web.xml using <context-param>.

ServletConfig

ServletConfig is an object created by web container to initialize single servlet. This object is used to get configuration information from web.xml for the single servlet using <init-param>

Scope Objects

Web components share information by means of objects that maintained as attributes of 4 scope objects.

  • WebContext
  • Session
  • Request
  • Page

Filtering request and response

A filter is an object use to modify the header and content of a request or response by intercepting. Filters can be used for authentication, logging etc. Request or response can be filtered by a chain of zero, one, or more filters in a specific order. Filters can be configured in web.xml using <filter>