There’s only one ServletContext for an entire web app, and all the parts of the web app share it. But each servlet in the app has its own ServletConfig. The Container makes a ServletContext when a web app is deployed, and makes the context available to each Servlet and JSP (which becomes a servlet) in the web app.
Web app initialization:
Container reads the DD and creates a name/value String pair for each <context-param>.
Container creates a new instance of ServletContext.
Container gives the ServletContext a reference to each name/value pair of the context init parameters.
Every servlet and JSP deployed as part of a single web app has access to that same ServletContext.
Don’t confuse ServletConfig parameters with ServletContext parameters!
You really have to keep these straight on the exam, and it’s tricky. You MUST know that both ServletConfig and ServletContext have init parameters, and both have the same getter method—getInitParameter(). BUT... you also have to know that context init parameters are set with <context-param> (not inside a <servlet> element) while servlet init parameters use <init-param> inside the individual <servlet> declarations in the DD.
If the app is distributed, there’s one ServletContext per JVM!
If your application is distributed across multiple servers (probably in a clustered environment), your web app really COULD have more than one ServletContext. A ServletContext is one per app, but only if the app is in a single JVM!
In a distributed environment, you’ll have one ServletContext per JVM. Now, chances are this won’t create problems, but if you have a distributed web app, you better consider the consequences of having different contexts for each JVM.
There are no Dumb Questions
Think of init parameters as deploy-time constants!
You can get them at runtime, but you can’t set them. There’s no setInitParameter().
Code Magnets
Rearrange the magnets to form a DD that declares a parameter that matches the servlet code:
getServletContext().getInitParameter("foo");
You won’t use all of the magnets!
(Note: when you see <web-app ... >, remember that this is our short-cut to save space on the page. You can’t deploy a web.xml file unless the <web-app> tag has all the attributes it needs.)
If you see “init parameter” without knowing if it means servlet or context init parameter, assume servlet.
Some people use the phrase “init parameter” to mean “servlet init parameter”, and they use “context parameter” or even “application parameter” to mean “context init parameter”. So, even though BOTH are initialization parameters, and both come from the getInitParameter() method, remember that only SERVLET init parameters are listed in the DD as init parameters, so the phrase “init parameter” means “servlet init parameter” by default. We know that as a developer, you’ll be kinder to others and always say explicitly whether an init parameter is a servlet init parameter or a context init parameter.