Friday, October 16, 2009

ServletContext and ServletConfig

ServletConfig

  • The servlet gets the init params from the ServletConfig. Each servlet has a ServletConfig object.

  • When the container initializes a servlet, it makes a unique ServletConfig object for it.

  • The servlet init params are read only once and is available only for that particular servlet.

  • The init params are given in the DD within the < servlet> tag.
 <servlet>  
 <init-param>  
 <param-name> name </param-name>  
 <param-value> val </param-value >  
 </init-param>  
 </servlet>  
  • The container first reads the DD and gets the init-params.

  • Then the container creates a new ServletConfig instance for the servlet

  • Container creates a new name/value pair of Strings for each init parameter

  • Container gives the ServletConfig reference to name/value pair

  • Container creates a instance of the servlet class

  • Container calls the init(ServletConfig) method by passing the ServletConfig reference

  • The servlet can access the init params using getServletConfig().getInitParameter("name")

    ServletContext

    The ServletContext is for the webapp. The container makes a ServletContext when a web application is deployed and makes it available to all the servlets and JSPs of that application. Context init params are available to the entire webapp. Any servlet and JSP in the app has access to the context init params. The context params are given in the DD outside the < servlet > tag.

    < web-app .... >
    < context-param >
    < param-name > name < /param-name >
    < param-value > val < /param-value >
    < /context-param >
    < servlet > < /servlet>
    < /we-app >

    The container reads the DD and creates name/value String for each context-param.
    Container creates a instance of ServletContext.
    Container gives the ServletContext reference to each name/value pair of the context params.
    Every JSPs and servlets deployed in that webapp can access this context params through the ServletContext using the method getServletContext().getInitParameter("name")

    Followers