O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

So what else can you do with your ServletContext?

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.

image with no caption
image with no caption

Note

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required