Java ServletContext

我有一个JSP网站,而不是Spring MVC,它有一个配置文件web.xml。

我想在web.xml文件中有几个设置。

但是,我想从位于Source Packages文件夹中的类中访问这些设置。

我知道我可以将ServletContect从JSP传递给类,但我想避免这种情况,只需从我的类中访问web.xml文件。

这可能吗?

编辑

我一直在看javax.servlet想我想要的是在那里,但如果它是我看不到它。

使用javax.servlet.ServletContextListener实现,它允许类似于单例的上下文访问:

 package test.dummy; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; public class ContextConfiguration implements ServletContextListener { private static ContextConfiguration _instance; private ServletContext context = null; //This method is invoked when the Web Application //is ready to service requests public void contextInitialized(ServletContextEvent event) { this.context = event.getServletContext(); //initialize the static reference _instance _instance=this; } /*This method is invoked when the Web Application has been removed and is no longer able to accept requests */ public void contextDestroyed(ServletContextEvent event) { this.context = null; } /* Provide a method to get the context values */ public String getContextParameter(String key) { return this.context.getInitParameter(key); } //now, provide an static method to allow access from anywere on the code: public static ContextConfiguration getInstance() { return _instance; } } 

在web.xml上设置:

    test.dummy.ContextConfiguration      

并在代码的任何地方使用它:

 ContextConfiguration config=ContextConfiguration.getInstance(); String paramValue=config.getContextParameter("parameterKey"); 

我认为这与你的描述非常接近: 链接 。

基本上,你想以编程方式从web.xml读取参数,对吧?

嗯…我假设一旦你的网络应用程序启动,那么你不会在web.xml中做任何改变….

现在你可以做的是创建一个servlet,它在启动时加载并初始化一个单例类。 您可以在web.xml中使用以下设置。

    XMLStartUp XMLStartUp com.test.servlets.XMLStartUp  log4j-init-file WEB-INF/classes/log4j.properties  0  

在tomcat中,如果设置load-on-startup值为0 ,则表示加载时它具有最高优先级。 现在在servlets init方法中读取所有这样的init-parameters并在你的singleton类中设置它。

 String dummy= getInitParameter("log4j-init-file"); 

这不容易实现,可能不是一个优雅的解决方案。 我建议的唯一选择是将配置选项设置为xml或属性文件,并将其放在WEB-INF / classes目录中,以便使用ClassLoader.getResourceClassLoader.getResourceAsStream查找。

我知道这可能是配置的重复,但IMO是一种重复的方式。

我真的不喜欢从web.xml中读取的类…为什么需要它? 恕我直言,如果你准备了一个属性文件和一个从那里读取的管理器类,它会更容易,更清晰,更易于管理。