views:

20

answers:

0

I am using Tomcat server in java and wanted to be able to access the ServletContext from the restlet Resource in order to access my cached DataSource object (to pool mysql connections). org.restlet.resource.Resource comes with a Context object but that is not in any way related to the ServletContext. So after some googling around, I found the following:

final String contextKey = "org.restlet.ext.servlet.ServletContext";
final String poolKey = "MyCachedDBPool";
final Map<String, Object> attrs = getContext().getAttributes();
final ServletContext ctx = (ServletContext) attrs.get(contextKey);
if (ctx == null) {
  throw new Exception("Cannot find ServletContext: " + contextKey);
}
final DataSource ds = (DataSource) ctx.getAttribute(poolKey);
if (ds == null) {
  throw new DetourQAException("DataSource not stored in context" 
    + poolKey + "attr");
}

But it returns null for the ServletContext. Has anybody successfully accessed the ServletContext from within the restlet resource and how did you do it?

If this is not the recommended way to do connection pooling, what is the best way to do connection pooling in the restlet?