How to access `ServletContext` from within a Vaadin 7 app?

纵然是瞬间 提交于 2019-11-27 23:07:35
Basil Bourque

tl;dr

For both Vaadin 7, 8 and 10:

VaadinServlet.getCurrent().getServletContext()

VaadinServlet

The VaadinServlet class inherits a getServletContext method.

To get the VaadinServlet object, call the static class method getCurrent.

From most anywhere within your Vaadin app, do something like this:

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

CAVEAT
Does not work in background threads. In threads you launch, this command returns NULL. As documented:

In other cases, (e.g. from background threads started in some other way), the current servlet is not automatically defined.

@WebListener (ServletContextListener)

By the way, you are likely to want to handle such global state when the web app deploys (launches) in the container.

You can hook into your Vaadin web app’s deployment with the @WebListener annotation on your class implementing the ServletContextListener interface. Both methods of that interface, contextInitialized and contextDestroyed, are passed a ServletContextEvent from which you can access the ServletContext object by calling getServletContext.

@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();
        // …
    }

}

This hook is called as part of your Vaadin app being initialized, before executing the Vaadin servlet (or any other servlet/filter in your web app). To quote the doc on the contextInitialized method:

Receives notification that the web application initialization process is starting. All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!