ServletContext initialization parameters are configuration values that are shared across the entire web application.
These parameters are defined once in the deployment descriptor (web.xml) and can be accessed by any servlet, filter, or listener within the application.
Unlike servlet initialization parameters which are specific to individual servlets, context parameters are application-wide and provide a centralized way to configure application settings.
The ServletContext provides two main methods for reading initialization parameters:
String getInitParameter(String paramName)
Enumeration<String> getInitParameterNames()
The
getInitParameter(String)
method returns the value of the specified parameter, or null if the parameter does not exist.
The
getInitParameterNames()
method returns an enumeration of all parameter names defined in the context.
Context initialization parameters are defined in the web.xml deployment descriptor using the
<context-param>
element:
<context-param>
<param-name>PARAM_NAME</param-name>
<param-value>PARAM_VALUE</param-value>
</context-param>
These parameters are loaded when the web application starts and remain constant throughout the application's lifecycle.
They are commonly used for database connection strings, file paths, configuration flags, and other application-wide settings that should not be hardcoded in the servlet classes.
Example implementation:
-
web.xml:
<web-app>
<context-param>
<param-name>servletcontext_paramname_1</param-name>
<param-value>servletcontext_paramvalue_1</param-value>
</context-param>
<context-param>
<param-name>servletcontext_paramname_2</param-name>
<param-value>servletcontext_paramvalue_2</param-value>
</context-param>
</web-app>
-
MyServlet.java:
package com.mtitek.servlets.test1;
import java.io.IOException;
import java.util.Enumeration;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class MyServlet1 extends HttpServlet {
@Override
public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
Enumeration<String> initParameterNames = getServletContext().getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String initParameterName = (String) initParameterNames.nextElement();
String initParameterValue = getServletContext().getInitParameter(initParameterName);
System.out.println(initParameterName + " : " + initParameterValue);
}
}
}
-
tomcat-stdout:
servletcontext_paramname_1 : servletcontext_paramvalue_1
servletcontext_paramname_2 : servletcontext_paramvalue_2