Registering a Spring Web Filter
Useful Spring Filters
Spring allows you to create web filters for intercepting Http Requests. It is useful to know abstract class org.springframework and some of its children:
- Spring Web
- OncePerRequestFilter: abstract class to be applied in filters that need to be applied for every HTTP Request.
- CharacterEncodingFilter: it adds character encoding if missing to HTTP Request and HTTP Response.
- RequestContextFilter: it exposes current Locale and current HTTP Request in the current thread as static variable (in the LocaleContextHolder and RequestContextHolder).
- CommonsRequestLoggingFilter: it logs with Commons Log, the request URI and optionally, the query string.
- ForwardedHeaderFilter: it parses Forwarded and X-Forwarded-* headers so Spring returns the client information accordingly.
- RelativeRedirectFilter: it adds Location headers and HTTP status on running local redirections.
- Spring Boot Web:
- ApplicationContextHeaderFilter: it adds the application context id to the X-Aplication-Context header in the HTTP Response.
- OrderedCharacterEncodingFilter: CharacterEncodingFilter that supports ordering.
- OrderedRequestContextFilter: RequestContextFilter that supports ordering.
Registering a filter
In order to register a filter, we just need to return a new instance of org.springframework.boot.web.servlet.FilterRegistrationBean, specifying the filter to register, the url patterns for which the filter should apply and the order.
Filters can be executed several times, for example on forwarding the request of one servlet to another. In order to ensure that the filter is only applied once for every request, our filter should extend OncePerRequestFilter. See here more info about OncePerRequestFilter.