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 would have to use getServletContext() to get a reference to the ServletContext object.

Q:

Q: How do all the parts of a web app get access to their own ServletContext?

A:

A: For servlets, you already know: call your inherited getServletContext() method.

For JSPs it’s a little different—JSPs have something called “implicit objects”, and ServletContext is one of them. You’ll see exactly how a JSP uses a ServletContext when we get to the JSP chapters.

Q:

Q: So you get built-in logging through your context? That sounds VERY helpful!

A:

A: Um, no. Not unless you have a really small, simple web app. There are much better ways to do logging. The most popular, robust logging mechanism is Log4j; you can find it on the Apache site at:

http://logging.apache.org/log4j

You can also use the logging API from java.util.logging, added to J2SE in version 1.4.

It’s fine to use the ServletContext log() method for simple experiments, but in a real production environment, you will almost certainly want to choose something else. There’s a good reference on web app logging with and without Log4j in the Java Servlet & JSP Cookbook from O’Reilly.

Logging is not part of the exam objectives, but it’s important. Fortunately, you’ll find the APIs easy to use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset