Java.Servlets.What is ServletContext?

If ServletConfig is like a servlet’s private config, then ServletContext is like a global shared workspace for the entire web application.

🌍 What Is ServletContext?

ServletContext is an object provided by the servlet container that:

✅ Represents the web application’s runtime environment and
✅ Provides a way for all servlets to share information and resources

📦 Key Use Cases of ServletContext:

Use CaseExample
Sharing data between servletsStore an object globally with setAttribute()
Reading global configGet app-level parameters from web.xml
Accessing resourcesLoad files with getResource() or getRealPath()
LoggingWrite to server logs via log()
Getting environment detailsServer info, context path, MIME types, etc.

🧪 Example: Sharing Data Between Servlets

Servlet A — set attribute:

@Override
public void init() {
    getServletContext().setAttribute("appStartTime", System.currentTimeMillis());
}

Servlet B — get attribute:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    Long startTime = (Long) getServletContext().getAttribute("appStartTime");
    res.getWriter().write("App started at: " + startTime);
}

✅ Works across all servlets in the same app.

📄 web.xml – Global Init Parameters

<context-param>
    <param-name>globalSetting</param-name>
    <param-value>enabled</param-value>
</context-param>

Servlet:

String value = getServletContext().getInitParameter("globalSetting");

🔧 Useful Methods in ServletContext

MethodPurpose
getInitParameter(String)Get app-wide init param from web.xml
getAttribute(String)Get a shared app-wide attribute
setAttribute(String, Object)Set a shared app-wide attribute
removeAttribute(String)Remove an attribute
getRealPath(String)Get physical path on the server
getResource(String)Get resource as URL
getMimeType(String)Get MIME type based on file extension
getContextPath()Get the web app’s context root (like /myapp)
log(String)Write to server log

🧠 ServletContext vs ServletConfig

FeatureServletConfigServletContext
ScopePer servletEntire web app
Data SharingNot sharedShared between all servlets
Defined in<servlet><context-param>
PurposeServlet-specific configApp-level config & resource sharing
AccessgetServletConfig()getServletContext()

🧩 Real Use Case Example

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    ctx.setAttribute("appStartTime", Instant.now());
}

This is from a ServletContextListener — perfect for setting shared values at startup.

✅ Summary

ConceptDescription
What is it?A global config and data-sharing object for the entire app
Provided byServlet container
Shared?Yes — among all servlets, filters, listeners
Typical UsesConfig, file access, logging, data sharing
Access viagetServletContext() in servlet or ServletContextListener
This entry was posted in Без рубрики. Bookmark the permalink.