问题
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?
回答1:
This was the way to do it before Restlet 2.0 (actually I think they changed it around 2.0-M5, or so). Anyway, the way you'd do it now is:
ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );
Hope that helps.
来源:https://stackoverflow.com/questions/3893386/java-accessing-servletcontext-from-within-restlet-resource