Access to OSGi framework functionality from a JSP is very simple. The Web Container will prepare the servlet context with the bundle's OSGi bundle context bound to the osgi-bundlecontext
attribute.
The Java code can be embedded in the JSP as follows:
<% BundleContext ctx = (BundleContext) getServletContext().getAttribute("osgi-bundlecontext");
This bundle context is the same that would have been passed to a BundleActivator
, if one were defined.
ServiceReference ref = ctx.getServiceReference(BookshelfService.class.getName());
Getting an instance of the BookshelfService
is then straightforward:
BookshelfService bookshelf = (BookshelfService) ctx.getService(ref); %>
Alternatively, the code can be moved outside of the JSP, into a JavaBean. We will create a SessionBean
, in which will be kept references to session information such as the bookshelf service reference and the session ID.