Introduction to Servlet

Servlets came into the Java world to help develop Web Applications. Web applications run over the web and are consumed by end user. It should not be confused with Web Services, which are consumed by a program as opposed to end user. A typical example of Web Application would be a Shopping Kart Application, which can be accessed over HTTP protocol from a web browser.
What are Servlet?
  • A Servlet is a Java program that runs on a Web Container. The Web Container is capable of handling HTTP requests and responses.

  • Servlets act as an inter-mediatory interface between HTTP requests originated from Web Browsers (IE, Chrome etc) and Java Applications hosted on Application Servers

  • Servlet runs as a light-weight thread instead of a separate OS process. This is opposed to a CGI script in which a new OS process is created for each request, making it heavy-weight and impacting performance.

  • Servlets can be used to collect form inputs from a page.

  • Servlet specification is released by Oracle, which vendors implement to create their own Web Containers.

  • Most popular Open Source Web Containers are: Apache Tomcat, Jetty and Glassfish.

  • A Servlet can run on any web container as it is developed using a common Servlet-API. For details refer: http://www.oracle.com

  • We must import javax.servlet.*; javax.servlet.http.*; in order to create a servlet.

    • Servlet Container
    • The most popular Servlet Container today is Tomcat. It is very light-weight and easy to develop and deploy applications on Tomcat.

    • Originally Tomcat was built by Sun MicroSystems, and later was handed over to the Apache Software Foundation in October 1999.

    • It can be easily integrated with all popular IDE's (like Eclipse, NetBeans etc) and promotes ease of development.

What is Server-side ?
Server-side development is the process of creating applications which run on a 'server' rather than on the end-users 'client' computer. The application running on Server can then be accessed by several clients simultaneously keeping processing centralized at one place.
What is Client-side ?
Client side language is required to create a webpages for faster responses. Client side languages work on the browser itself saving flow of information over the network and hence improving performance.

Why Build Web Pages Dynamically?
A dynamic web page is a page that changes based on the user. It responds to the user's needs, and provides necessary information to meet them, by accessing information in a connected database.

Difference Between Server Side And Client Side

Client Side Server Side
Client Side programs run on the user's computer. Server side codes are executed in server and result is displayed in web browser as HTML.
Client Side programming is less secure. Server-side scripts are more secure than client-side.
The code which is run on the user's computer using scripts like Javascript can or may be blocked. Server-side scripting does not have any limitation of any browser.
What is CGI:-
  • CGI came prior to servlets. It gave an standard approach to pass and receive user's request to an application program using HTTP protocol.

  • Problem with CGI was that it was heavy-weight as separate process was created with each request, not allowing application to scale up.

Servlets vs CGI:-
  • CGI programs are platform dependent while servlets are platform independent.

  • CGI programs run as separate processes on the computer while servlets runs as light-weight threads improving performance.

  • CGI can directly process scripts while Servlet needs to be compiled before it can be run as a servlet to process client requests.

  • Servlets are more secure compared to CGI Scripts.

  • CGI Web Server
    Servlet vs CGI
Advantages of Servlet:-
  • Each request is run in a seperate thread, so servlet request processing is significantly faster than traditional CGI processing.
  • Servlet is scalable.
  • Servlets are robust and Object Oriented.
  • Servlets are platform independent.
  • The Web-container provides additional services to the servlets, such as error handling & security.
  • Servlet API:-
    • The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.
    • All servlets must implement the Servlet interface, which defines life-cycle methods.
    Servlet API


    Servlet:-
    It defines Life Cycle methods that all Servlets must implement.

    Method Description
    void init(ServletConfig config)
    throws ServletException
    Called the when Servlet is initialized or created. Web Container calls the init method exactly once after instantiating the Servlet. An UnavailableException is thrown if the servlet cannot be intialized.
    public ServletConfig
    getServletConfig()
    Returns ServletConfig object.
    public void service(ServletRequest req,
    ServletResponse res)
    throws ServletException, IOException
    Called by the Web Container to allow the servlet to respond to a request. Parameters: Object of ServletRequest(req) that contains the client's request and Object of ServletResponse(res)that contains the servlet's response. An IOException is thrown if IO problem occurs.
    String getServletInfo() Returns a String containing information about Servlet.
    public void destroy() Called when the servlet is unloaded (being taken out of service method). Happens during web-container shut down.
    ServletConfig:-
    The ServletConfig interface is implemented by the server. It allows a servlet to get information about Configuration during it's initialization.

    Method Description
    String getInitParameter(String name) Returns a String which contains the value of the initialization parameter and name which defines names of initialization parameter.
    Enumeration getInitParameterNames() Returns Enumeration of String objects containing the names of all initialization parameters.
    public ServletContext getServletContext() Returns the reference of ServletContext.
    Generic Servlet:-
    It is abstract class.

    GenericServlet implements the Servlet, ServletConfig, Serializable interfaces.

    It implements some lifecycle methods.

    GenericServlet may be directly extended by a servlet, Even though it's more common to extend a protocol-specific subclass such as HttpServlet.

    Method Description
    void log(String s) It writes the specified message to a servlet log file.
    void log(String s, Throwable e) It writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file.
    Http Servlet:-
    It is an abstract class and extends the Generic Servlet. To create your own Servlet, you need to subclass HttpServlet.
    A subclass of HttpServlet must override at least one methods listed below:
    Method Description
    protected void doGet(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException,
    IOException
    Called by the server through service() to allow a servlet to handle a GET request. Parameters: Object HttpServletRequest(req) that contains the request the client has made of the servlet. Object of HttpServletResponse(resp) that contains the response the servlet sends to the client
    protected void doPost(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException
    Called by the server through service() to allow a servlet to handle a POST request. Parameters: Object of HttpServletRequest(req) that contains the request the client has made of the servlet. Object of HttpServletResponse that contains the response the servlet sends to the client.
    protected long getLastModified(
    HttpServletRequest req)
    Returns last modified time in miliseconds.
    protected void doHead(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException
    protected void doPut(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException.
    Called by the server to allow a servlet to handle a PUT requests. Parametrs: Object of HttpServletRequest(req)that contains the request the client made of the servlet. Object of HttpServletResponse(resp) that contains the response the servlet returns to the client.
    protected void doTrace(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException
    Called by the server to allow a servlet to handle a TRACE request.
    protected void service(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException
    Receives standard HTTP and responds by calling doXXX() method defined in the servlet.
    doOptions protected void doOptions(
    HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException
    Called by the server to allow a servlet to handle a OPTIONS request.
    HttpServlet GenericServlet
    HttpServlet defines a HTTP protocol specific servlet. GenericServlet defines a generic, protocol-independent servlet.
    It inherit generic servlet class. It implements servlet interface.
    It use doGet and doPost method instead of service. It use service method.