Context Parameter and Init Parameter in Servlets

Context Parameter and Init Parameter in Servlets
The deployment descriptor can include configuration information for Servlet.

There are 2 types of Parameters,

  • Context Parameters
  • Init Parameters

 

Context Parameter Init Parameter
Context Parameter are declared outside the Servlet
and can be used anywhere in
web application
Init Parameters are declared inside the servlet
and can be used only within
that servlet
Reading Context Parameters: String context=
this.getServletContext().getInitParameter(“paramname”);
Reading Init Parameter, there are 2 ways –
1) String name=
this.getInitParameter(“paramname”);
2) name=
getServletConfig().getInitParameter
(“paramname”);

Context Param with param name “sname” and value “Alpha” is declared in web.xml
Init Param with param name “ename” and value “Beta” is declared inside servlet in web.xml
Web.xml

struct1

In  web.xml we can see that, Context Param is declared independent of Servlets so context-param value can be used anywhere in entire web application and in any Servlets.
Init param is declared inside servlet1, so can be used only inside servlet1.

For our understanding, lets create couple of JSP pages and Servlets,

Match.jsp – Inside body enter “<h1> Value Matched </h1>”
error.jsp – Inside body enter “<h1> Mismatch Error </h1>”

servlet.java
servlet1.java

Init Parameter Example:
Init Parameter is declared in Servlet1, lets check Servlet1 first:
servlet.java

Output:

op1
Init parameter is declared in servlet1, so the value is matched and Match.jsp showed.
Now lets try with Servlet2.java

Servlet2.java

Output:
op2
Since Init parameter is declared and valid only inside servlet.java, it works inside that. So when we tried with servlet1.java we were taken to error page.

Context Parameter Example:
servlet2.java

Output:
op1
servlet3.java

Output:
op1
Since context parameters are independent of Servlets, it takes us to match page.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *