Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing the servletContext outside of a servlet

 
Jonathan Wood
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64830
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jonathan Wood
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic