Java从restlet资源中访问ServletContext

发布于 2024-09-26 09:10:53 字数 852 浏览 2 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唠甜嗑 2024-10-03 09:10:53

这是 Restlet 2.0 之前的做法(实际上我认为他们在 2.0-M5 左右更改了它)。不管怎样,你现在要做的就是:

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

希望有帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文