问题描述
我在java中使用Tomcat服务器并希望能够从restlet资源访问ServletContext以访问我的缓存DataSource对象(以池化mysql连接)。 org.restlet.resource.Resource附带一个Context对象,但它与ServletContext没有任何关系。所以经过一些谷歌搜索,我发现以下内容:
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");
}
但它为ServletContext返回null。有没有人从restlet资源中成功访问了ServletContext,你是怎么做到的?
But it returns null for the ServletContext. Has anybody successfully accessed the ServletContext from within the restlet resource and how did you do it?
如果这不是推荐的连接池方式,那么最好的方法是什么?在restlet中做连接池?
If this is not the recommended way to do connection pooling, what is the best way to do connection pooling in the restlet?
推荐答案
这是在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:
ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );
希望有所帮助。
这篇关于Java从restlet资源中访问ServletContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!