aspose file tools*
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 Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Accessing the servletContext outside of a servlet" Watch "Accessing the servletContext outside of a servlet" New topic
Author

Accessing the servletContext outside of a servlet

Jonathan Wood
Greenhorn

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
Sheriff

Joined: Dec 11, 2004
Posts: 13410

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

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContextEvent.html


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

Joined: Jan 10, 2002
Posts: 61063
    
  66

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
Greenhorn

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!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing the servletContext outside of a servlet