> For the complete documentation index, see [llms.txt](https://anon-coders-notes.gitbook.io/techwriterdev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anon-coders-notes.gitbook.io/techwriterdev/languages/java/01_backend/05_aboutservlet/regarding_servletcontext.md).

# 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
