2010-10-08 99 views
4

我在java中使用Tomcat服務器,並希望能夠從Restlet Resource訪問我的緩存的DataSource對象(用於池連接mysql)中的ServletContext。 org.restlet.resource.Resource帶有一個Context對象,但與ServletContext沒有任何關係。因此,經過一些谷歌搜索後,我發現以下內容:從restlet中訪問ServletContext的Java資源

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"); 
} 

但是它返回null爲ServletContext。有人從restlet資源中成功訪問了ServletContext,你是如何做到的?

如果這不是推薦的連接池方式,那麼在restlet中執行連接池的最佳方式是什麼?

回答

6

這是在Restlet 2.0之前做到這一點的方式(實際上我認爲他們將它改爲2.0-M5左右)。無論如何,你現在這樣做的方式是:

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

希望有所幫助。

+0

謝謝,我會試試看。但是我最終使用了一個靜態變量,而不是試圖使用servlet來存儲它。 – 2010-12-01 22:54:59