我有一个 JSP 网站,而不是 Spring MVC,它有一个配置文件 web.xml。
我想要获取 web.xml 文件中的一些设置。
但是,我想从“源包”文件夹中的类中访问这些设置。
我知道我可以将 ServletContext 从 JSP 传递到类,但我想避免这种情况,只从我的类访问 web.xml 文件。
这可能吗?
EDIT
我一直在看javax.servlet
我想我想要的东西就在那里,但即使是,我也看不到它。
Using a 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 中进行设置:
<web-app>
<listener>
<listener-class>
test.dummy.ContextConfiguration
</listener-class>
</listener>
<servlet/>
<servlet-mapping/>
</web-app>
并从代码中的任何位置使用它:
ContextConfiguration config=ContextConfiguration.getInstance();
String paramValue=config.getContextParameter("parameterKey");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)