Java从restlet资源中访问ServletContext
我在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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 Restlet 2.0 之前的做法(实际上我认为他们在 2.0-M5 左右更改了它)。不管怎样,你现在要做的就是:
希望有帮助。
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:
Hope that helps.