A ServletContext is a JSP or servlet’s connection to both the Container and the other parts of the web app. Here are some of the ServletContext methods. We put the ones you should know for the exam in bold.
You can get a ServletContext in two different ways...
A servlet’s ServletConfig object always holds a reference to the ServletContext for that servlet. So don’t be fooled if you see servlet code on the exam that says:
getServletConfig().getServletContext().getInitParameter()
Not only is that legal, but it does the same thing as:
this.getServletContext().getInitParameter()
In a servlet, the only time you would NEED to go through your ServletConfig to get your ServletContext is if you’re in a Servlet class that doesn’t extend HttpServlet or GenericServlet (the getServletContext() method you inherit comes from GenericServlet). But the chance of ANYONE using a non-HTTP servlet is, well, asymptotically approaching zero. So just call your own getServletContext() method, but don’t be dazed or confused if you see code that uses the ServletConfig to get the context.
But what if the code is inside some class that is NOT a servlet (a helper/utility class, for example)? Someone might have passed a ServletConfig to that class, and the class code would have to use getServletContext() to get a reference to the ServletContext object.