# Servlet Context

* Defined in,

```java
  javax.servlet.ServletContext (i/f)
```

* Instance of ServletContext interface's implementation class is created by the container at the application deployment time.
* Only **one** instance is created per web application.
* _NOTE : The ServletContext object is contained within the ServletConfig object, which the WC provides to the servlet once the servlet is initialized._
* Usages
  *   Server side logging.

      ```java
        //Interface ServletContext
        public void log(String mesg)
      ```
  *   To create context scoped _(Application scoped)_ attributes.

      ```java
        public void setAttribute(String name,Object val)
      ```

      _NOTE : Access them always in thread safe manner. as they are mutable as it is a server side object._
*   To access global scoped _(application scoped)_ attributes use,

    ```java
     //Interface ServletContext
      Object getAttribute(String name)
    ```
*   To add context scoped attributes

    ```java
      void setAttribute(String name, Object object)
    ```
* web.xml tags to create context parameters, no annotations available

```xml
<context-param>
  <param-name>name</param-name>
  <param-value>value</param-value>
</context-param>
```

* To access these parameters in a Servlet once the Servlet instance has initialized i.e init() method has been called.

1. Get ServletContext
   * API of GenericServlet

```java
  public ServletContext getServletContext() //method inherited from GenericServlet
```

2. ServletContext API String getInitparameter(String paramName) : returns the parameter value. eg : ctx param name : user\_name value : abc In the Servlet : getServletContext().getInitparameter("user\_name") ---abc

5.4 Creating request dispatcher H.W
