4

我在 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 中进行连接池的最佳方式是什么?

4

1 回答 1

6

这是在 Restlet 2.0 之前的方式(实际上我认为他们在 2.0-M5 左右改变了它)。无论如何,你现在的做法是:

ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );

希望有帮助。

于 2010-11-30T02:25:34.647 回答