Spring Security’s servlet support relies on the servlet Filter
API.
This means that it can work with any application that runs in a servlet container.
It does not require that you use Spring in any other part of your application.
Spring Security’s servlet container support (whether you run in Apache Tomcat or other servlet container) is built on top of the Filter
API.
This is done because the Filter
API is a standard that allows injecting logic into an application in any servlet container.
Since Spring Security is built on top of javax.servlet.Filter
objects.
It will greatly benefit you if you understand the concept of interceptors and how Filter
objects work.
The following example shows a simple Filter
implementation:
Example 8.1. SimpleFilter Example
public class SimpleFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { // optional initialization } // invoked every request the Filter is mapped for public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Before"); chain.doFilter(request, response); System.out.println("After"); } public void destroy() { // optional cleanup } }
Important | |
---|---|
If |
A servlet Filter
lets us apply logic around the rest of the application.
This means that we can perform logic before, conditionally invoke the rest of the application, and perform logic afterwards in any servlet container.
In order for a servlet Filter
to be invoked, it must be registered with the servlet container.
The following example shows how to do so in XML:
Example 8.2. web.xml
In Java configuration, you can use a ServletContextListener
.
The following example shows how to do so:
Example 8.3. RegisterServletContextListener.java
@WebListener public class FilterStartupListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); FilterRegistration fltrReg = ctx.addFilter("simpleFilter", SimpleFilter.class); EnumSet<DispatcherType> dispatchers = EnumSet.of(DispatcherType.REQUEST); boolean isMatchAfter = true; fltrReg.addMappingsForUrlPatterns(dispatchers, isMatchAfter, "/*"); } }
Define the | |
In Java configuration, we must explicitly provide the Section 8.1.3, “Dispatch Types”. | |
In Java configuration, we must explicitly indicate whether the | |
Provide one more mapping for the Filter.
In this case, |