Question
What is the difference between <init-param> and <context-param> in Java EE?
Answer
In Java EE applications, configuration parameters play a crucial role in defining application behavior. Two common types of parameters used within the configuration files, specifically in the web.xml deployment descriptor, are <init-param> and <context-param>. While they serve similar purposes, there are significant differences between them.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<init-param>
<param-name>myParam</param-name>
<param-value>someValue</param-value>
</init-param>
</servlet>
<context-param>
<param-name>globalParam</param-name>
<param-value>globalValue</param-value>
</context-param>
Causes
- <init-param> is used to define parameters specific to a servlet, whereas <context-param> is used for application-wide parameters.
Solutions
- <init-param> is only applicable in the context of the servlet it is associated with; it cannot be accessed by other servlets unless explicitly passed.
- <context-param> is accessible by all servlets and components within the web application, making it ideal for global configurations.
Common Mistakes
Mistake: Assuming <init-param> can be accessed outside its servlet scope.
Solution: Always remember that <init-param> is limited to the servlet it is defined in.
Mistake: Using <context-param> for servlet-specific configurations.
Solution: Use <context-param> for parameters that should be accessible application-wide instead.
Helpers
- <init-param>
- <context-param>
- Java EE configuration
- servlet parameters
- web.xml parameters