【问题标题】:Java accessing ServletContext from within restlet ResourceJava 从 restlet 资源中访问 ServletContext
【发布时间】:2011-04-23 01:04:36
【问题描述】:

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

【问题讨论】:

    标签: java connection-pooling restlet servlets


    【解决方案1】:

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

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

    希望对您有所帮助。

    【讨论】:

    • 谢谢,我试试。但我最终使用了一个静态变量,而不是尝试使用 servlet 来存储它。
    猜你喜欢
    • 2011-01-21
    • 2012-04-27
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 2021-10-29
    • 2011-10-23
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多