In the previous topic we saw how frameworks can add the web components dynamically by implementing ServletContainerInitializer as opposed to the old style of web.xml configuration on the application side. But there are things where we still need the deployment descriptor e.g. ordering of components, list of welcome pages, login and error pages etc.
Servlet 3.0 introduced the notion of web module deployment descriptor fragments (web fragment). Now we can do all those web.xml configuration in our jar project in META-INF/web-fragment.xml file and bundle the project as a library or framework.
As we mentioned before, jar level annotation scanning can be turned off by using metadata-complete="true" , that applies to web fragments too. By turning off scanning, the application is responsible to provide all necessary configuration in it's own web.xml .
Example Project
In this example we are going to extend the example from last topic. This time, we are also going to bundle servlet container managed, form based authentication functionality. The idea is, the client side developer should be free from writing commonly repeated code. The framework should bundle as much functionality as it can.
In this example, we would need deployment descriptor (web-fragment.xml ) to configure <security-constrain> along with <login-config> . We would also specify <error-page> . We are going to include couple of JSP pages too. As last example there's going to be two projects, one for the framework and other one for the framework client
Creating the Framework project based on Web Fragment
- Prepare project
- Create a simple maven project (name it
servlet-fragment-framework ) using your IDE or maven-archetype-quickstart . See an example here.
- In
pom.xml add dependencies of javax.servlet-api:3.0.1 and jstl:1.2.
- Create implementation of
ServletContainerInitializer as AppInitializer as we did in the last example.
- Create the file
META-INF/services/javax.servlet.ServletContainerInitializer and put fully qualified class name of AppInitializer in it.
- Create a servlet class
AppController .
- Create
web-fragment.xhtml and specify all security stuff etc.
- Create JSP pages under
META_INF/resources . META-INF must be in your class path. As we are using maven project, I put that into main maven's resources folder.
- Now as this project is not executable, we are just going to install it in local repository using
mvn clean install We will include this project's dependency in our client project.
Dependencies and Technologies Used: - Java Servlet API 3.0.1
- javax.servlet:jstl 1.2
- JDK 1.8
- Maven 3.0.4
|