Spring Boot Custom Filter
In this tutorial, will demonstrate how to implement custom filter or to add filters with Spring Boot rest api and different options to configuring these filters.
What are Filters?
Filter is a javax.servlet
interface that can be used to do filtering on a request to a
resource (a
servlet or static content), on the response from a resource, or both. It is, in reality, an object
that is used to intercept your application's HTTP requests and responses.
In the Spring Boot application, there are a few ways to register custom filters. We will perform action before rest controller request and also before reaches the client.
Project Structure
Spring Boot Custom Filter
Create a new Custom Filter by implementing filter interface. The highest-order filter is the first to execute. This comes in handy when we want to run our custom filters in a specific order.
package com.techgeeknext.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomValidationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomValidationFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("======== In Init CustomValidationsFilter filter =========");
}
@Override
public void doFilter(ServletRequest servletRequest
, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
LOGGER.info("CustomValidationsFilter Request Details {} : {}",
httpServletRequest.getAuthType(), httpServletRequest.getRequestURI());
// you can also check for auth type
/* if(httpServletRequest.getAuthType()!=null){
.....
....
}*/
//check for validation
if (httpServletRequest.getRequestURI().equalsIgnoreCase("/welcome")) {
//initiate next filter
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
LOGGER.info("CustomValidationsFilter Response Status : {}", httpServletResponse.getStatus());
}
@Override
public void destroy() {
LOGGER.info("======= Destroy CustomValidationsFilter =========");
}
}
Take a look at our suggested posts:
Custom Filters
We can write additional filters that will be executed after the first. We can also use @Order(1)
or
@Order(2)
to add Order, depending on the order in which the filters will be executed.
package com.techgeeknext.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class CustomLoginFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomLoginFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("======== In Init CustomLoginFilter filter =========");
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
// check for valid url
if(verifyValidURL(filterChain, httpServletRequest, httpServletResponse)) {
//call for next filter
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
LOGGER.info("CustomLoginFilter Response Status : {}", httpServletResponse.getStatus());
}
@Override
public void destroy() {
LOGGER.info("########## Destroying CustomLoginFilter filter ##########");
}
private boolean verifyValidURL(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
LOGGER.info("Requested URL : {}", request.getRequestURI());
// we can add business logic to check here that Requested URL have any invalid or junk code
if(request.getRequestURI()
.equalsIgnoreCase("/welcome")){
return true;
}
return false;
}
}
Test Filters
Start the Spring Boot application by using mvn spring-boot run
command and use rest
endpoint http://localhost:8282/welcome .
You can see the filter got applied and logs got printed in the console.
15:29:14.705 INFO 38140 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8282 (http)
15:29:14.734 INFO 38140 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
15:29:14.735 INFO 38140 --- [main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.30]
15:29:14.949 INFO 38140 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
15:29:14.949 INFO 38140 --- [main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3067 ms
15:29:15.035 INFO 38140 --- [main] c.t.filters.CustomValidationFilter
: ======== In Init CustomValidationsFilter filter =========
15:29:15.037 INFO 38140 --- [main] c.t.filters.CustomLoginFilter
: ======== In Init CustomLoginFilter filter =========
15:29:15.502 INFO 38140 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
15:29:15.847 INFO 38140 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8282 (http) with context path ''
15:29:15.865 INFO 38140 --- [main] c.t.SpringBootFilterExampleApplication : Started SpringBootFilterExampleApplication in 5.242 seconds (JVM running for 6.074)
15:29:47.182 INFO 38140 --- [nio-8282-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
15:29:47.182 INFO 38140 --- [nio-8282-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
15:29:47.195 INFO 38140 --- [nio-8282-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 13 ms
15:29:47.202 INFO 38140 --- [nio-8282-exec-1] c.t.filters.CustomValidationFilter
: CustomValidationsFilter Request Details null : /welcome
15:29:47.217 INFO 38140 --- [nio-8282-exec-1] c.t.filters.CustomLoginFilter
: Requested URL : /welcome
15:29:47.291 INFO 38140 --- [nio-8282-exec-1] c.t.filters.CustomLoginFilter
: CustomLoginFilter Response Status : 200
15:29:47.291 INFO 38140 --- [nio-8282-exec-1] c.t.filters.CustomValidationFilter
: CustomValidationsFilter Response Status : 200
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Custom Filter Example