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

What if you want an app init parameter that’s a database DataSource?

image with no caption

Context parameters can’t be anything except Strings. After all, you can’t very well stuff Dog object into an XML deployment descriptor. (Actually, you could represent a serialized object in XML, but there’s no facility for this in the Servlet spec today... maybe in the future.)

What if you really want all the parts of your web app to have access to a shared database connection? You can certainly put the DataSource lookup name in a context init parameter, and that’s probably the most common use of context parameters today.

But then who does the work of turning the String parameter into an actual DataSource reference that all parts of the web app can share?

You can’t really put that code in a servlet, because which servlet would you choose to be The One To Lookup The DataSource And Store It In An Attribute? Do you really want to try to guarantee that one servlet in particular will always run first? Think about it.

Flex Your Mind

How could you solve this problem?

How could you initialize a web app with an object? Assume that you need the String context init parameter in order to create that object (think about the database example).

image with no caption

What she really wants is a listener.

She wants to listen for a context initialization event, so ...

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