tl;dr
For Vaadin 7 & 8, as well as Vaadin Flow (versions 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…