问题
How do I access the current ServletContext from within my Vaadin 7 app?
I want to use the ServletContext
object’s setAttribute, getAttribute, removeAttribute, and getAttributeNames methods to manage some global state for my Vaadin app.
Also, if using those methods for that purpose is inappropriate for Vaadin apps, please explain.
回答1:
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.
来源:https://stackoverflow.com/questions/27933599/how-to-access-servletcontext-from-within-a-vaadin-7-app