Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
The moose likes Servlets and the fly likes Accessing the servletContext outside of a servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Accessing the servletContext outside of a servlet" Watch "Accessing the servletContext outside of a servlet" New topic

Accessing the servletContext outside of a servlet

Jonathan Wood

Joined: Jan 12, 2005
Posts: 2
This may be a stupid question, but i am trying to create a "global" database connection object for my web app using a servletContextListener and setting it as a context attribute. I have a plain old bean that i want to get the connection from the servletContext but cannot. Inside my bean i have:


Connection con = (Connection) getServletContext().getAttribute("DbStudents");


but get the compile error: "Cannot resolve symbol method getServletContext()"

Is this because the servletContext can only be accessed from a Servlet?
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

There is a ServletContextEvent object passed to your contextInitialized method. That object has a getServletContext method.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 62317

Think about it for a minute, how could your plain old bean have an implementation of getServletContext() unless you added one?

Your bean needs the connection (I strongly advise looking into connection pooling rather than using a single global connection), so pass the connection to the bean. It'd be a poor practice to force your bean to be servlet-aware, so you shouldn't be thinking along the lines of passing the servlet context to the bean just so it could pluck out an attribute.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Jonathan Wood

Joined: Jan 12, 2005
Posts: 2
Hi guys... thanks for the quick responses - I understand how the listener works in that it has the event which i extract the context reference too etc. It was in my bean that I was not sure how to then access the context from, and, if it was possible. I looked at an example of setting up the db connection as a resource-ref with pooling and am going that route - thx!!!
subject: Accessing the servletContext outside of a servlet