本文介绍了如何在简单的类文件中获取ServletContext对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的Web应用程序.我需要在该类中获取对ServletContext对象的引用.我怎么能得到它?

I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?

推荐答案

最好将其作为参数传递给对象的构造函数,或使用setter方法进行设置.

You'd better pass it as argument to the constructor of your object, or set it using a setter method.

实际上,您可以获取与对象相关的context属性,并仅通过构造函数/setter传递它.例如:

In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example:

YourClass obj = 
    new YourClass((AnotherClass) servletContext.getAttribute("yourAttribute"));


更糟糕,更复杂的选择是:


A much worse and more complication option is to:

  1. 创建一个 ServletContextListener
  2. 使用< listener>< listener-class></listener-class></listener>
  3. 在web.xml中注册
  4. contextInitialized(..)上从事件中获取 ServletContext 并将其存储在单个实例中-某个静态字段.
  1. Create a ServletContextListener
  2. register it in web.xml with <listener><listener-class></listener-class></listener>
  3. on contextInitialized(..) get the ServletContext from the event and store it in a singleton - a static field somehwere.

或者,您可以使用 ServletRequestListener 对每个请求执行此操作,并将其存储在 ThreadLocal 中.

Alternatively, you can do this on each request, using a ServletRequestListener and store it in a ThreadLocal instead.

然后您可以通过调用单例/threadlocal持有者来获取值,如下所示:

Then you can obtain the value via calling your singleton/threadlocal holder like this:

ServletContextHolder.getCurrentServletContext()

这篇关于如何在简单的类文件中获取ServletContext对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:35