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

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.