Update: One of the Answers by Leif Åstrand explains both methods are actually present in Vaadin 14 but one is undocumented.
I verified that we can indeed call:
ServletContext servletContext = VaadinServlet.getCurrent().getServletContext();
So the rest of my Answer here is obsolete. I will leave my Answer as a curiosity, rather than delete it.
This may not be the best way, but it seems to be working for me.
The VaadinServletService
class, extending com.vaadin.flow.server.VaadinService
, offers the getCurrentServletRequest()
. That method returns a javax.servlet.http.HttpServletRequest
object. For there we can call javax.servlet.ServletRequest.getServletContext
to return the javax.servlet.ServletContext
you desire.
ServletContext servletContext =
VaadinServletService // com.vaadin.flow.server.VaadinServletService
.getCurrentServletRequest() // Returns a javax.servlet.http.HttpServletRequest
.getServletContext() // Returns a `javax.servlet.ServletContext`.
;
From there you can use the key-value "attribute" collection as you mentioned. Look to the setAttribute
, getAttribute
, and removeAttribute
methods with a String
object as the key and a Object
as the value.
Saving.
DataSource dataSource = … ;
VaadinServletService.getCurrentServletRequest().getServletContext().setAttribute( "javax.sql.DataSource" , dataSource ) ;
Retrieving. The key-value collection of "attributes" keep the value as an Object
, so we must cast back to the expected class/interface.
DataSource dataSource = (DataSource) VaadinServletService.getCurrentServletRequest().getServletContext().getAttribute( "javax.sql.DataSource" ) ;