Java Reference
In-Depth Information
you also need to consider the case where servlets come before or after an
Http-
Service
. Hence you need similar logic in the
bindServlet()
method, shown in the
next code snippet.
Listing 15.5 Binding servlets in the OSGi service registry using iPOJO (continued)
@Bind(aggregate=true)
void bindServlet(Servlet servlet, Map attrs) {
String ctx = (String) attrs.get("Web-ContextPath");
if (ctx != null) {
LinkedList<HttpService> snapshot;
B
Reads web
context path
C
Stores servlet and snapshots
available HTTP Services
synchronized (servlets) {
servlets.put(ctx, servlet);
snapshot = new LinkedList<HttpService>(services);
}
D
Registers servlet
with available
HTTP Services
for (HttpService s : snapshot) {
try {
s.registerServlet(ctx, servlet, null, null);
} catch (ServletException e) {
log.log(LogService.LOG_WARNING, "Failed to registerServlet", e);
} catch (NamespaceException e) {
log.log(LogService.LOG_WARNING, "Failed to registerServlet", e);
}
}
}
}
In this method, you read the
Web-ContextPath
from the service headers
B
. If this
isn't
null
, you then snapshot the
HttpService
s and store the servlet using the same
object lock as in listing 15.4—ensuring that you don't miss any services
C
. Finally, you
iterate over the available
HttpService
s and register the new servlet
D
.
The final piece of the puzzle is the actual registration of a servlet. Here you create
the trivial
HelloServlet
shown in the following listing, which prints a message in the
web browser.
Listing 15.6 Binding servlets in the OSGi service registry using iPOJO (continued)
@Component(immediate = true)
@Provides(specifications = Servlet.class)
public class HelloServlet extends HttpServlet {
@ServiceProperty(name = "Web-ContextPath")
String ctx = "/hello";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
...
}
}
You register this component using the
Servlet
interface and add the
Web-Context-
Path
service property with i
POJO
annotations.