![]() |
VOOZH | about |
ServletConfig and ServletContext are important interfaces in Java Servlets used for configuration and communication. ServletConfig is used to store servlet-specific initialization parameters, while ServletContext is used to share data across the entire application. Together, they help manage configuration and enable communication between servlets.
ServletConfig is an object that contains initialization parameters for a specific servlet. It is created by the servlet container and passed to the servlet during initialization.
Syntax
ServletConfig config = getServletConfig();
String value = config.getInitParameter("param-name");
Example: The following example demonstrates how ServletConfig is used to provide servlet-specific initialization parameters that are accessible only to a single servlet.
web.xml
RecruiterServlet.java
Output:
Recruiter Contact Email: recruiter@jobportal.com
Explanation:
ServletContext is an object that holds application-wide configuration information. It is shared among all servlets in the web application.
Syntax
ServletContext context = getServletContext();
String value = context.getInitParameter("param-name");
Example: The example demonstrates how ServletContext is used to share application-wide configuration data that can be accessed by all servlets.
web.xml
AnyServlet.java
Output:
Website Name: NewWebsite.tg
Explanation:
| ServletConfig | ServletContext |
|---|---|
| ServletConfig is servlet specific | ServletContext is for whole application |
| Parameters of servletConfig are present as name-value pair in <init-param> inside <servlet>. | Parameters of servletContext are present as name-value pair in <context-param> which is outside of <servlet> and inside <web-app> |
| ServletConfig object is obtained by getServletConfig() method. | ServletContext object is obtained by getServletContext() method. |
| Each servlet has got its own ServletConfig object. | ServletContext object is only one and used by different servlets of the application. |
| Use ServletConfig when only one servlet needs information shared by it. | Use ServletContext when whole application needs information shared by it |