Java ServletContext [英] Java ServletContext

查看:70
本文介绍了Java ServletContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSP web site, not Spring MVC, and it has a config file web.xml.

web.xml中有几个设置我希望得到的文件。

There are a couple of settings within the web.xml file that I'd like to get.

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

However, I want to access those settings from within a class sitting in my Source Packages folder.

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

I know I can pass the ServletContect from the JSP to the class but I want to avoid this and just access the web.xml file from my class.

这可能吗?

编辑

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

I have been looking at javax.servlet thinking what I want was in there but if it is I can't see it.

推荐答案

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

Using a javax.servlet.ServletContextListener implementation, that allows a singleton-like access to context:

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设置:

Set it up at web.xml:

<web-app>
<listener>
    <listener-class>
     test.dummy.ContextConfiguration
    </listener-class>
  </listener>
<servlet/>
<servlet-mapping/>
</web-app> 

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

And use it from anywhere at the code:

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

这篇关于Java ServletContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆