As you all know, Spring Boot is a wonderful way of developing a web application or stand-alone application with minimum configuration and opinionated setup.
This is how I have achieved a web filter development in a Spring Boot application
My SpringBootApp specifications:
Spring Boot version: 2.0.4.RELEASE
Java version: 8.0
Servlet specification: Servlet 3.0 (Mandatory and Important)
I declared my web filter in the following manner, adhering to the Servlet specification 3.0
This is the programmatic way of defining a filter as a replacement to web.xml-based definitions.
The "@Webfilter" annotation will be processed by the container during deployment. The Filter class, in which it is found, will be created as per the configuration and applied to the URL patterns, javax.servlet.Servlets and javax.servlet.DispatcherTypes.
To avoid Web.xml completely and to achieve "Deployable" WebApp:
To deploy a Spring Boot application as "Traditional WAR", the application class should extend SpringBootServletInitializer.
NOTE:
SpringBootServletInitializer is a "programmatic implementation" of web.xml with reference to the Servlet 3.0+ specifications, which requires an implementation of WebApplicationInitializer.
Thus, SpringBootApplication doesn't require "web.xml" as its application class (after extending SpringBootServletInitializer). It scans for
- @WebFilter,
- @WebListener and
- @WebServlet.
Annotation @ServletComponentScan
This annotation enables scanning base packages for the web components annotated with @WebFilter, @WebListener and @WebServlet.
Due to the fact that embedded containers do not support @WebServlet, @WebFilter and @WebListener annotations, Spring Boot, relying greatly on embedded containers, introduced this new annotation @ServletComponentScan to support some dependent JAR files that use these three annotations.
Scanning is only performed when using an embedded Servlet container.
The following is my Spring Boot application class definition:
Custom Servlet Initializer:
Here: I have defined a custom class: "ServletInitializer" which extends Class: SpringBootServletInitializer.
As explained earlier, SpringBootServletInitializer is responsible for scanning annotations:
- @WebFilter,
- @WebListener and
- @WebServlet.
And hence the Spring Boot application class should
- Either extend the class: SpringBootServletInitializer or
- extend the custom class which extends the class: SpringBootServletInitializer