如何在没有任何请求,会话等的情况下获取上下文?

时间:2014-10-31 08:54:48

标签: java spring tomcat servlets

我在类中有一个方法,没有任何可用于获取实际servlet上下文的方法。实际上,它就像

public String getSomething() { ... }

但是为了计算结果,我需要实际的,特定于线程的servlet结构。

我认为,在应用程序上下文的某个深处,某些类似于特定于线程的存储应该存在,这可以通过调用某些系统类的静态方法来实现。

我在一个tomcat6 servlet容器中,但如果需要,Spring也可用。

4 个答案:

答案 0 :(得分:7)

web.xml添加ServletContextListener。这将在您的webapp加载时调用。在contextInitialized()方法中,您可以将ServletContext存储在静态变量中,以供日后使用。然后,您将能够以静态方式访问ServletContext

class MyListener implements ServletContextListener {

    public static ServletContext context;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        context = sce.getServletContext();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        context = null;
    }

}

将其添加到web-xml,如下所示:

<web-app>
    <listener>
        <listener-class>
            com.something.MyListener
        </listener-class>
    </listener>
</web-app>

您可以从以下任何地方访问它:

public String getSomething() {
    // Here you have the context:
    ServletContext c = MyListener.context;
}

注意:

您可能希望将其存储为private并提供getter方法,并在使用前检查null值。

答案 1 :(得分:3)

一个显而易见的解决方案是将上下文作为参数传递,因为您显然正在运行上下文通常可用的代码。

如果由于某种原因你觉得这不是你可以做的事情(我想听听它的原因),另一种方法是创建一个servlet过滤器,然后创建例如{{1} }。

答案 2 :(得分:2)

如果你没有指向有用的东西,我知道的唯一方法是在包含当前ServletContext的类中有一个静态属性。使用ServletContextListener

是微不足道的
@WebListener
public class ServletContextHolder implements ServletContextListener {
    private static ServletContext servletContext;

    public static ServletContext getServletContext() {
        return servletContext;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        servletContext = null;
    }    
}

然后从你使用的任何地方

ServletContextHolder.getServletContext();

如果您使用Spring,您还可以使用RequestContextHolder获取当前请求的访问权限(从那里到您需要的任何内容)

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                                 .getRequestAttributes()).getRequest();

当然如果在servlet应用程序中以这种方式工作而不是在portlet中工作 - 你必须使用PortletRequestAttributes并最终得到一个PortletRequest

答案 3 :(得分:1)

您可以自动连接servlet上下文,如下所示

@Autowired
ServletContext servletContext;