# SERVLET CONFIG

* A **servlet specific** configuration object created by a servlet container(W.C) to pass information to a servlet during initialization.

Defined in

```java
  //interface
  javax.servlet.ServletConfig 
```

* Servlet Config's empty instance is created by the Web container(WC) after instantiation of servlet instance and before call to init() using `dependency injection`.
* To pass **servlet specific** initialization parameters, we need this servlet config instance, as we cannot pass servlet specific initialization parameter through default constructor() _there is no parametrized servlet constructor_. _(i.e the init-param is accessible to one servlet only or you can say that the init-param data is private for a particular servlet.)_
* Where to add these servlet specific initialization parameters?
  * Can be added either in `web.xml` or `@WebServlet` annotation.
  *   But preferable is `web.xml` so as to keep these configuration external to java code, so that changes to java source code and hassles of recompilation can be avoided.

      * XML Tags

      ```xml
        <servlet>
            <servlet-name>init</servlet-name>
            <servlet-class>ex.TestInitParam</servlet-class>
            <!- 
            the below tags are used to pass servlet specific init parameters
            one tag per initialization parameter
            ->
            <init-param>
              <param-name>name</param-name>
              <param-value>value</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
          <servlet-name>init</servlet-name>
          <url-pattern>/test_init</url-pattern>
        </servlet-mapping>
      ```

      * Annotations

      ```java
        @WebServlet(
          value="/url-pattern", 
          initParams= {@WebInitParam(name="some_name", value="some_value")})
      ```
* To access servlet specific initialization parameters from a servlet, override the `init()` method.
*   To get Servlet Config object of the servlet class use,

    ```java
      //Method of javax.servlet.GenericServlet
      public ServletConfig getServletConfig()
    ```
* To get the init parameters from ServletConfig

```java
  //Method of ServletConfig i/f
  String getInitparameter(String name) 
  //rets the parameter value.
```
