如何在Vaadin 7应用程序中访问`ServletContext`?

10

如何在我的 Vaadin 7 应用程序中访问当前的 ServletContext

我想使用 ServletContext 对象的 setAttributegetAttributeremoveAttributegetAttributeNames 方法来管理一些全局状态,以供我的 Vaadin 应用程序使用。

如果对于 Vaadin 应用程序而言,使用这些方法来实现该目的是不合适的,请进行解释。


1个回答

24

简短易懂版

针对Vaadin 7和8以及Vaadin Flow(版本10+):

VaadinServlet.getCurrent().getServletContext()

VaadinServlet

VaadinServlet 类继承了 getServletContext 方法。

要获取 VaadinServlet 对象,请调用静态类方法 getCurrent

从 Vaadin 应用程序的大多数位置,可以执行以下操作:

ServletContext servletContext = VaadinServlet.getCurrent().getServletContext();

注意
本命令无法在后台线程中运行。在您启动的线程中,此命令将返回NULL。正如文件所述:

在其他情况下(例如从以某种其他方式启动的后台线程中),当前servlet不会自动定义。

@WebListenerServletContextListener

顺便提一下,当Web应用程序在容器中部署(启动)时,您可能想要处理这种全局状态。

您可以使用@WebListener注释来挂钩您的Vaadin Web应用程序部署,该注释应该放在实现ServletContextListener接口的类上。该接口的两个方法contextInitializedcontextDestroyed都会传递一个ServletContextEvent,通过调用getServletContext方法,您可以访问ServletContext对象。请注意保留HTML标签。
@WebListener ( "Context listener for doing something or other." )
public class MyContextListener implements ServletContextListener
{

    // Vaadin app deploying/launching.
    @Override
    public void contextInitialized ( ServletContextEvent contextEvent )
    {
        ServletContext context = contextEvent.getServletContext();
        context.setAttribute( … ) ;
        // …
    }

    // Vaadin app un-deploying/shutting down.
    @Override
    public void contextDestroyed ( ServletContextEvent contextEvent )
    {
        ServletContext context = contextEvent.getServletContext();
        // …
    }

}

这个 hook 作为您的 Vaadin 应用程序初始化的一部分被调用,在执行 Vaadin servlet(或 Web 应用程序中的任何其他 servlet/filter)之前。引用文档中 contextInitialized 方法的内容:

接收到 Web 应用程序初始化过程即将开始的通知。 在 Web 应用程序中初始化任何过滤器或 servlet 之前,所有 ServletContextListeners 都会收到上下文初始化的通知。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接