Understanding ServletConfig and ServletContext: Initialization Parameters, Data Sharing, Request Forwarding, Resource Access, and Client‑Side Caching in Java Web Applications
This article provides a comprehensive tutorial on using ServletConfig and ServletContext in Java web development, covering how to configure and retrieve servlet initialization parameters, share data between servlets, forward requests, read resource files, and set client‑side caching for servlet responses, with complete code examples.
1. ServletConfig Overview
ServletConfig allows you to define initialization parameters for a servlet in web.xml . These parameters are packaged into a ServletConfig object and passed to the servlet during its init method.
1.1 Configuring Servlet Initialization Parameters
Example web.xml configuration:
<servlet>
<servlet-name>ServletConfigDemo1</servlet-name>
<servlet-class>gacl.servlet.study.ServletConfigDemo1</servlet-class>
<!-- Configure initialization parameters -->
<init-param>
<param-name>name</param-name>
<param-value>gacl</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123</param-value>
</init-param>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</servlet>1.2 Retrieving Initialization Parameters via ServletConfig
When the servlet is created, the container injects a ServletConfig instance. You can obtain parameters with config.getInitParameter("name") and enumerate all parameters.
package gacl.servlet.study;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletConfigDemo1 extends HttpServlet {
private ServletConfig config;
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String paramVal = this.config.getInitParameter("name");
response.getWriter().print(paramVal);
response.getWriter().print("
");
Enumeration
e = config.getInitParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
String value = config.getInitParameter(name);
response.getWriter().print(name + "=" + value + "
");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}2. ServletContext Object
The web container creates a single ServletContext instance for each web application. It can be obtained from ServletConfig.getServletContext() or directly via getServletContext() . All servlets in the same application share this object, enabling inter‑servlet communication.
3. Applications of ServletContext
3.1 Data Sharing Between Servlets
Example: ServletContextDemo1 stores a value in the context, and ServletContextDemo2 retrieves it.
// ServletContextDemo1
package gacl.servlet.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "xdp_gacl";
ServletContext context = this.getServletConfig().getServletContext();
context.setAttribute("data", data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} // ServletContextDemo2
package gacl.servlet.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String data = (String) context.getAttribute("data");
response.getWriter().print("data=" + data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}Running ServletContextDemo1 stores the string, and ServletContextDemo2 reads it, demonstrating shared data.
3.2 Accessing Web‑Application Initialization Parameters
Define global parameters in web.xml using <context-param> :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- Configure global initialization parameters -->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>Retrieve the parameter in a servlet:
package gacl.servlet.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String contextInitParam = context.getInitParameter("url");
response.getWriter().print(contextInitParam);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}3.3 Request Forwarding Using ServletContext
Servlet ServletContextDemo4 forwards the request to ServletContextDemo5 via RequestDispatcher .
package gacl.servlet.study;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo4 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "
abcdefghjkl
";
response.getOutputStream().write(data.getBytes());
ServletContext context = this.getServletContext();
RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} package gacl.servlet.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo5 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getOutputStream().write("servletDemo5".getBytes());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}Accessing ServletContextDemo4 displays the content generated by ServletContextDemo5 , demonstrating successful forwarding.
3.4 Reading Resource Files with ServletContext
Various examples show how to read properties files located in src , WEB-INF/classes , and the web‑root directory using ServletContext methods such as getResourceAsStream and getRealPath . The code prints the loaded configuration values (driver, url, username, password) to the response.
4. Client‑Side Caching of Servlet Output
For data that changes infrequently, you can set an Expires header to let browsers cache the response, reducing server load.
package gacl.servlet.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo5 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "abcddfwerwesfasfsadf";
// Cache the response for 1 day
response.setDateHeader("expires", System.currentTimeMillis() + 24 * 3600 * 1000);
response.getOutputStream().write(data.getBytes());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}Setting the Expires header to one day allows browsers to reuse the cached content without contacting the server for each request.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.