javax.servlets

  • Life Cycle:lifecycle of a servlet contains the following stages
    1. Instantiation: Web container creates an instance of the servlet
    2. Initialization: Container calls the instances init() method if not called earlier.
    3. Service: If the container has a request for the servlet, it calls the servlet instances service() method.
    4. Destroy: Before destroying the instance, the container calls the servlet instances destroy() method.
    5. Unavailable: The instance is destroyed and marked for garbage collection.
  • Types of Servlets
    Servlets must implement the interface javax.servlet.Servlet.
    There are two main types of servlets:
    1. Generic servlets extend javax.servlet.GenericServlet. Generic servlets are protocol independent, meaning that they contain no inherent support for HTTP or any other transport protocol.
    2. HTTP servlets extend javax.servlet.HttpServlet. These servlets have built-in support for the HTTP protocol and are much more useful in an Browser environment
  • Request Types
    1. doGetGET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns no body in the response, only the request header fields.
      If the request is incorrectly formatted, doGet returns an HTTP “Bad Request” message.
      The GET method should be safe, that is, without any side effects for which users are held responsible
      Appends the form values to the URL (max 256 chars)
    2. doPost The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information.
      The servlet container must write the headers before committing the response
    3. doPut The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.
      It may be useful to save a copy of the affected URL in temporary storage.
    4. doDelete DELETE operation allows a client to remove a document or Web page from the server.
      It may be useful to save a copy of the affected URL in temporary storage.
    5. doTrace A TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging.
      No need to override this method
    6. doHead The client sends a HEAD request when it wants to see only the headers of a response, such as Content-Type or Content-Length
      Set the response headers directly to improve performance
    7. doOptions OPTIONS request determines which HTTP methods the server supports and returns an appropriate header.
      No need to override this method
  • HTTP GETs
    An HTTP GET request can be affected in a number of ways:
    An HREF tag associated with text or an image.
    Image maps that allow specific areas of an image to target a given URL when clicked.
    JavaScript onclick=’location=’ associated with a visible and click able DOM object.
    A FORM with ACTION=GET and a submit action invoked either through an associated INPUT TYPE=SUBMIT button, or a JavaScript submit action associated with a browser event

    Advantage Dis-Advantage
    Is the most efficient way to transfer control from one state to the next, especially where the next state is pure HTML that may be already cached by the browser. The ability to transfer data to the target state is limited to the URL query string, which has definite size limitations.
    Pages invoked with an HTTP GET can be easily bookmarker to return to the same page with the same data where dynamic content is involved.  
  • HTTP POSTs
    Once a FORM context has been established, there are two primary mechanisms by which control is actually transferred:
    Clicking an INPUT TYPE=SUBMIT button associated with the FORM. The JavaScript FORM. Submit function, usually associated with a button or other click able type.
    Once the link is established, triggering the associated event (such as clicking the link) will cause the POST request to be issued to the Web server. Usually, POST requests must be handled by a Web application component, such as a servlet or JSP.

    Advantage Dis-Advantage
    There are no absolute limits to the amount of data that can be passed to the web server as part of the request. Also, the data passed does not appear on the location line of the browser.. If an HTTP POST request needs to be reinvaded due to a browser event, telling the user to reload the page.
    The browser will warn the user if the request needs to be re-invoked. A POST request is that it cannot be book marked because the associated data is not available in the URL query string.
  • Multi vs Single Threaded
    Multi Single
    When the OS supports multiple thread of execution within a single process When the OS does not recognize the concept of thread
    By default the servlets operate on multi threaded model. More than one thread can access the service method concurrently guaranteed that no two threads will execute concurrently in the servlet’s service method
    Does not takes care of synchronization of code Single Threaded model interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet.
  • Servlet Context
    Defines a servlet view of the web application, & provides access to resources and facilities (logging) common to all servlets in the application.
    Servlet Context interface only provides access to information about the servlet environment such as name of server, MIME Type mapping & etc.
    Servlet Context (spec 2.2) is rooted at a specific path in the web server.
    Servlet context interface encapsulates the notion of a context for a web application via getServletContext()
  • Servlet Collaboration
    In the default servlet model, a servlet receives an HTTP request, executes some application logic and prepares the response.
    There are many cases when a Servlet receives a request and needs to prepare response from another resource.
    Two types of solution
    Servlet Chaining: This is not supported by the servlet API spec
    Request Dispatching: Allows 1 servlet to dispatch the request to another resource.
  • Request Forwarding
    To transfer control directly from the servlet to JSP without involving the client.
    Forward method should be called before the response has been committed to the client. If the response already has been committed, this method throws an IllegalStateException.
    javax.servlet.RequestDispatcher rd = request.getRequestDispatcher(“OutputJSP.jsp”);
    rd.forward (request, forward);
  • Application lifecycle events: : These events provide the enterprise developer greater control over interactions with ServletContext & HttpSession objects.
    1. javax.servlet.ServletContextListener
      A ServletContextListener receives notification about the ServletContext of the web application.
      The application server notifies the listener when the application server initializes & destroys the web application.
      Listeners of this event must implements the following methods
      Public void contextDestroyed (javax.servlet.ServletContextEvent)
      Public void contextInitialized (javax.servlet.ServletContextEvent)
      ServletContextEvent provides a getServletContext method to retrieve the related ServletContext
    2. javax.servlet.ServletContextAttributeListener
      A ServletContextAttributeListener receives notification when attributes in the ServletContext change.
      Listeners of this event must implements the following methods
      Public void attributeAdded (javax.servlet.ServletContextAttibuteEvent)
      Public void attributeRemoved (javax.servlet.ServletContextAttibuteEvent)
      ServletContextAttributeEvent provides a getName and getValue method to inspect the related attribute
    3. javax.servlet.HttpSessionListener
      HttpSessionListener receives notification when changes occur to a session of the web application.
      Listeners of this event must implements the following methods
      Public void sessionCreated (javax.servlet.http.HttpSessionEvent)
      Public void sessionDestroyed (javax.servlet.http.HttpSessionEvent)
      HttpSessionEvent provides a getSession method to retrieve the related Session
    4. javax.servlet.HttpSessionAttributeListener
      HttpSessionAttributeListener receives notification when changes occur to the attributes stored in session
      Listeners of this event must implements the following methods
      Public void attributeAdded (javax.servlet.http.HttpSessionBindingEvent)
      Public void attributeRemoved (javax.servlet.http.HttpSessionBindingEvent)
      Public void attributeReplaced (javax.servlet.http.HttpSessionBindingEvent)
      HttpSessionBindingEvent provides a getSession method to retrieve the related Session and getName, getValue methods to retrieve the related attributes.
  • Filters
    Is typically used to provide additional processing before or after the invocation of a servlet.
    Filters can be used for logging & auditing, image conversion, data compression, encryption, tokenizing, and even XSL transformation.
    Filters must implement 3 methods:
    Init : called once by the application server, initializes the filter, enabling it to acquire any needed resources.
    doFilter: is where the main processing of the filter takes place. The application server calls the doFilter method once for each request of the associates servlet.
    Destroy: called once by the application server, allows the filter to release any resources acquired in the init method.
  • Send-ReDirect vs Request Dispatcher
    Send-ReDirect Request Dispatcher
    response.sendRedirect(“fileName.jsp”); RequestDispatcher reqDispr = servletContext.getRequestDispatcher (“fileName.jsp”);
    reqDispr.forward(request, response);
    Control is transferred when the whole service method completes Control is transferred immediately (when you call the forward() method)
  • What is the difference between GenericServlet and HttpServlet?
    GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet. The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.
  • What is the difference between ServletContext and ServletConfig?
    Both are interfaces. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet’s init() method.The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
  • How HTTP Servlet handles client requests?
    An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

Life Cycle:lifecycle of a servlet contains the following stages Instantiation: Web container creates an instance of the servlet Initialization: Container calls the instances init() method if not called earlier. Service: If the container has a request for the servlet, it calls the servlet instances service() method. Destroy: Before destroying the instance, the container calls the…

Leave a Reply

Your email address will not be published. Required fields are marked *