我在 java 中使用 Tomcat 服务器,并希望能够从 restlet 资源访问 ServletContext 以访问我缓存的 DataSource 对象(以池 mysql 连接)。org.restlet.resource.Resource 带有一个 Context 对象,但它与 ServletContext 没有任何关系。因此,经过一番谷歌搜索后,我发现了以下内容:
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");
}
但它为 ServletContext 返回 null。有没有人从 restlet 资源中成功访问了 ServletContext,你是怎么做到的?
如果这不是进行连接池的推荐方式,那么在 restlet 中进行连接池的最佳方式是什么?