Servlet 3.0 is part of Java EE 6 and offers dynamic servlet registration. This feature let us automatically register servlets without the need of a web deployment descriptor in our webapp. Spring already provides this for its own DispatcherServlet with SpringServletContainerInitializer.
This approach has for main advantage to use Java code and thus to compile-time type-checking. It would be nice to have the same one for Vaadin servlet. In order to achieve this, we need two classes, one entry-point and another for registration proper.
The registration class sole responsibility is to dynamically register the Vaadin servlet(s). We can design it however we choose, we need to access the servlet context for registration purpose. We also need to create programmatic setters to handle previously available servlet initialization parameters. Even better, we could choose to put in place sensible defaults. Here’s such an example:
Note the only method to implement is getUI() since it has to be customized for each web application. All methods provide sensible defaults but can be overriden should it be needed.
On the other hand, the entry-point implementation should do something like this: for each type referenced, instantiate it and calls it register() method. This leads to two requirements:
The final step is to implement a service provider: create a javax.servlet.ServletContainerInitializer file under META-INF/services and set its content to the fully-qualified name of SingleRootVaadinRegistar.
Compiling and packaging the above classes and resources in a JAR put in your WEB-INF/lib folder and extending SingleRootVaadinRegistar will achieve our goal. The extended class will register a Vaadin servlet, with the UI we returned.
Of course, coding those for every project is boring: it would be better to have a reusable component. There’s a shot at this on Vaadin directory.