我正在开发一个Web应用程序,该应用程序分布在一个tomcat实例中运行的多个上下文中。上下文用crossContext="true"
标记,以便我们可以在不同上下文之间共享一些jsp。 Tomcat的common.loader
中还包含一组通用类。我们很想改变这个结构,所以请在回答问题时对这个结构敏感。
我想做的就是获取所有存在于所有不同上下文中的资源,例如com.something.messages
。这是可能吗?我应该为创建的每个上下文记录类加载器并使用它加载资源吗?你有什么建议吗?
最佳答案
如果您已经在Servlet 3.0上,那么可以使用ServletContext#getClassLoader()
来获取Servlet上下文自己的类加载器:
ServletContext otherContext = servletContext.getContext("/other");
ClassLoader otherClassLoader = otherContext.getClassLoader();
// ...
(如果抛出安全异常,请相应地编辑策略文件)
然后,您可以将此类加载器传递到例如
ResourceBundle#getBundle()
中:ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, otherClassLoader);
// ...
如果由于各种原因(例如尚未使用Servlet 3.0,或者不愿意摆弄策略文件(非常合理...)等)而无法实现,那么最好的选择是给每个Web应用程序自己的
ServletContextListener
它加载所需的包并将其存储为ServletContext
方法期间的contextInitialized()
属性。这样,您可以按照通常的方式将其作为属性获取。