SERVLETS
Servlet

• Platform-    independent    Server   side
  components , written in Java which
  extends the standard web server and
  provide a general framework for services
  build on the Request –Response paradigm
• An Efficient and Powerful technology for
  creating dynamic content for the Web and
  fundamental part of all Java web
  technologies
Servlet Container
        The servlet container
is a part of a Web server or
application      server    that
provides       the     network
services        over     which
requests and responses
are sent, decodes MIME-
based requests, and formats
MIME-based responses. A
servlet      container     also
manages servlets through
their lifecycle.
Servlet API
javax.servlet.GenericServlet
• Signature: public abstract class GenericServlet extends
  java.lang.Object implements Servlet, ServletConfig,
  java.io.Serializable
• GenericServlet defines a generic, protocol-independent
  servlet.
• GenericServlet gives a blueprint and makes writing
  servlet easier.
• GenericServlet implements the log method, declared in
  the ServletContext interface.
• To write a generic servlet, it is sufficient to override the
  abstract service method.
javax.servlet.http.HttpServlet
• Signature: public abstract class HttpServlet extends
  GenericServlet implements java.io.Serializable
• HttpServlet defines a HTTP protocol specific servlet.
• HttpServlet gives a blueprint for Http servlet and makes
  writing them easier.
• HttpServlet extends the GenericServlet and hence
  inherits the properties GenericServlet.
Servlet Life Cycle
The Web container manages the life cycle of servlet instances

                                        New              Destroyed



                                              Running
                                 init(                      destroy(
                                 )                          )


                                                               ...(
                                              service(
                                                               )
                                              )
                               doGet(
                               )                              doDelete(
                                                              )
                                        doPost(     doPut(
                                        )           )
The init ( ) method
•    Called by the Web container when the servlet instance is first created
•    The Servlets specification guarantees that no requests will be processed by
     this servlet until the init method has completed
• Override the init() method when:
        i) You need to create or open any servlet-specific resources that you need
for processing user requests
        ii)You need to initialize the state of the servlet
//A simple servlet lifecycle counter
// int count ;
public void init(ServletConfig config) throws ServletException
     {
                    super.init(config);
                    getServletContext().log("init() called");
                    count=0;
         }
The service ( ) method
• Called by the Web container to process a user request
• Dispatches the HTTP requests to doGet(…),
  doPost(…), etc. depending on the HTTP request
  method (GET, POST, and so on)
   – Sends the result as HTTP response
• Usually we do not need to override this method

 protected void service(HttpServletRequest request, HttpServletResponse response) throws
 ServletException, IOException
      {
                        getServletContext().log("service() called");
                        count++;
                        response.getWriter().write("Incrementig the count: Count = "+count);

            }
The destroy() Method
•   Called by the Web container when the servlet instance is being eliminated ( All
    threads within the servlets service method have exited (or) Time-out period have
    passed )

•   The Servlet specification guarantees that all requests will be completely processed
    before this method is called
•   Override the destroy method when:
     – You need to release any servlet-specific resources that you had opened in the
        init() method
     – You need to persist the state of the servlet




     public void destroy() {
                       getServletContext().log("destroy() called");
              }
servletConfig
• Object of servletConfig used to pass initialization and
  context information to servlets
• getServletConfig ( ) method allows the servlet to retrieve
  the object and obtain configuration at anytime
• Init () method stores the servletConfig object in a private
  transient instance variable called config
ServletContext
• The javax.servlet.ServletContext interface provides a set of methods
  that the servlet can use to communicate with the web server.
• The       ServletContext      object     is     contained      within
  javax.servlet.ServletConfig Object which is provided to the servlet
  when it is initialized.
• Define URI to name mappings
• Allow Data to be shared between different servlets
• Contains a servlet log
• Access to global servlet config and other application servlet context
  are accessible
• It communicates with the server in a non request specific manner
Http Request and Response
            Structure
• HTTP is a stateless protocol.
• Server does not have the overhead of tracking client
  connections.
• HTTP transactions are either a request or response.
• Servlet can overcome the stateless nature of HTTP by
  tracking client state using session information stored in
  URL, hidden fields or cookies.
Http Transactions
A single request or response line
  – <HTTP Method>/<document address>HTTP/
    <Version No> e.g.
  – GET /index.html HTTP/1.1
  – Response line contains an HTTP status code.
  HTTP/1.1 200 OK
  Date:……………………….GMT
  Server:
  Last-modified:
  Content-type: text/html
  Content-length:….bytes
Http Servlet Methods
•   doGet()
•   doPost()
•   doHead()
•   doDelete()
•   doOptions()
•   doPut()
•   doTrace()
•   getLastModified()
•   service()
Http Servlet Request
• getMethod()
    – Returns get/post with which request was made.
•   getQueryString()
•   getRemoteUser()
•   getRequestSessionId()
•   getSession(boolean)
    – If FALSE returns current valid session otherwise
      creates a new session.
• isRequestedSessionIdValid()
• getCookies()
Http Servlet Response

• addCookie(Cookie)
  – Add cookie to response
• encodeUrl(String)
• sendRedirect(String)
• sendError(int)
Thread Safety
• Multithreaded = one servlet, multiple
  requests simultaneously
• Thread safe – not using class variables
  since one copy of these variables is
  shared by all threads
• Synchronized code blocks , all threads
  wait until they can enter, one at a time
• Servlet 2.4 deprecates SingleThreadModel
  interface – could not resolve all potential
  threading issues.

Servlets

  • 1.
  • 2.
    Servlet • Platform- independent Server side components , written in Java which extends the standard web server and provide a general framework for services build on the Request –Response paradigm • An Efficient and Powerful technology for creating dynamic content for the Web and fundamental part of all Java web technologies
  • 3.
    Servlet Container The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME- based requests, and formats MIME-based responses. A servlet container also manages servlets through their lifecycle.
  • 6.
  • 7.
    javax.servlet.GenericServlet • Signature: publicabstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable • GenericServlet defines a generic, protocol-independent servlet. • GenericServlet gives a blueprint and makes writing servlet easier. • GenericServlet implements the log method, declared in the ServletContext interface. • To write a generic servlet, it is sufficient to override the abstract service method.
  • 8.
    javax.servlet.http.HttpServlet • Signature: publicabstract class HttpServlet extends GenericServlet implements java.io.Serializable • HttpServlet defines a HTTP protocol specific servlet. • HttpServlet gives a blueprint for Http servlet and makes writing them easier. • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.
  • 9.
    Servlet Life Cycle TheWeb container manages the life cycle of servlet instances New Destroyed Running init( destroy( ) ) ...( service( ) ) doGet( ) doDelete( ) doPost( doPut( ) )
  • 10.
    The init () method • Called by the Web container when the servlet instance is first created • The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed • Override the init() method when: i) You need to create or open any servlet-specific resources that you need for processing user requests ii)You need to initialize the state of the servlet //A simple servlet lifecycle counter // int count ; public void init(ServletConfig config) throws ServletException { super.init(config); getServletContext().log("init() called"); count=0; }
  • 11.
    The service () method • Called by the Web container to process a user request • Dispatches the HTTP requests to doGet(…), doPost(…), etc. depending on the HTTP request method (GET, POST, and so on) – Sends the result as HTTP response • Usually we do not need to override this method protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getServletContext().log("service() called"); count++; response.getWriter().write("Incrementig the count: Count = "+count); }
  • 12.
    The destroy() Method • Called by the Web container when the servlet instance is being eliminated ( All threads within the servlets service method have exited (or) Time-out period have passed ) • The Servlet specification guarantees that all requests will be completely processed before this method is called • Override the destroy method when: – You need to release any servlet-specific resources that you had opened in the init() method – You need to persist the state of the servlet public void destroy() { getServletContext().log("destroy() called"); }
  • 13.
    servletConfig • Object ofservletConfig used to pass initialization and context information to servlets • getServletConfig ( ) method allows the servlet to retrieve the object and obtain configuration at anytime • Init () method stores the servletConfig object in a private transient instance variable called config
  • 14.
    ServletContext • The javax.servlet.ServletContextinterface provides a set of methods that the servlet can use to communicate with the web server. • The ServletContext object is contained within javax.servlet.ServletConfig Object which is provided to the servlet when it is initialized. • Define URI to name mappings • Allow Data to be shared between different servlets • Contains a servlet log • Access to global servlet config and other application servlet context are accessible • It communicates with the server in a non request specific manner
  • 15.
    Http Request andResponse Structure • HTTP is a stateless protocol. • Server does not have the overhead of tracking client connections. • HTTP transactions are either a request or response. • Servlet can overcome the stateless nature of HTTP by tracking client state using session information stored in URL, hidden fields or cookies.
  • 16.
    Http Transactions A singlerequest or response line – <HTTP Method>/<document address>HTTP/ <Version No> e.g. – GET /index.html HTTP/1.1 – Response line contains an HTTP status code. HTTP/1.1 200 OK Date:……………………….GMT Server: Last-modified: Content-type: text/html Content-length:….bytes
  • 17.
    Http Servlet Methods • doGet() • doPost() • doHead() • doDelete() • doOptions() • doPut() • doTrace() • getLastModified() • service()
  • 18.
    Http Servlet Request •getMethod() – Returns get/post with which request was made. • getQueryString() • getRemoteUser() • getRequestSessionId() • getSession(boolean) – If FALSE returns current valid session otherwise creates a new session. • isRequestedSessionIdValid() • getCookies()
  • 19.
    Http Servlet Response •addCookie(Cookie) – Add cookie to response • encodeUrl(String) • sendRedirect(String) • sendError(int)
  • 20.
    Thread Safety • Multithreaded= one servlet, multiple requests simultaneously • Thread safe – not using class variables since one copy of these variables is shared by all threads • Synchronized code blocks , all threads wait until they can enter, one at a time • Servlet 2.4 deprecates SingleThreadModel interface – could not resolve all potential threading issues.