Java ServletContext
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java ServletContext,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1677字,纯文字阅读大概需要3分钟。
内容图文
我有一个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上进行设置:
<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");
内容总结
以上是互联网集市为您收集整理的Java ServletContext全部内容,希望文章能够帮你解决Java ServletContext所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。