Scope in Servlets


  1. Context/Application Scope - javax.servlet.ServletContext

    Context/Application scope begins when a webapp is started and ends when it is shutdown or reloaded. Parameters/attributes within the application scope will be available to all requests and sessions. The Context/Application object is available in a JSP page as an implicit object called application.
    In a servlet, you can the object by calling getServletContext(). or by explicitly calling getServletConfig().getServletContext().
     
  2. Request Scope - javax.servlet.http.HttpServletRequest

    Request scope begins when an HTTP request is received by a servlet and end when the servlet has delivered the HTTP response. With respect to the servlet life cycle, the request scope begins on entry to a servlet’s service() method and ends on the exit from that method. Request object is available in a JSP page as an implicit object called request.
    A request object attribute can be set in a servlet and passed to a JSP within the same request.
  3. Session Scope -javax.servlet.http.HttpSession

    A session scope starts when a client (e.g. browser window) establishes connection with a webapp and continues till the point where the client, again read browser window, closes. Hence, session scope may span across multiple requests from the same client. In a servlet, you can get Session object by calling request.getSession() and in a JSP session.
     
  4. JSP page Scope - javax.servlet.jsp.PageContext

    The page scope restricts the scpoe and lifetime of attributes to the same page where it was created. It is available in a JSP page as an implicit object called pageScope .