Java accessing ServletContext from within restlet Resource

人走茶凉 提交于 2019-12-10 06:39:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3893386/java-accessing-servletcontext-from-within-restlet-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!