filter

add a filter in Spring Boot

Introduction

Filters as the name suggest used to perform filtering on either the request to a resource or on the response from a resource, or both. Spring Boot provides few options to register custom filters in the Spring Boot application.


Define Spring Boot Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class CustomURLFilter implements Filter {

private static final Logger LOGGER = LoggerFactory.getLogger(CustomURLFilter.class);

@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating Custom filter ##########");
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;

LOGGER.info("Logging Request {} : {}", request.getMethod(), request.getRequestURI());

// call next filter in the filter chain
filterChain.doFilter(request, response);

System.out.println(response.getOutputStream());

LOGGER.info("Logging Response :{}", response.getContentType());
}

@Override
public void destroy() {
LOGGER.info("destroy");
}

}

Register the custom Filter using FilterRegistrationBean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class AppConfig {

@Bean
public FilterRegistrationBean<CustomURLFilter> filterRegistrationBean() {
FilterRegistrationBean<CustomURLFilter> registrationBean = new FilterRegistrationBean();
CustomURLFilter customURLFilter = new CustomURLFilter();

registrationBean.setFilter(customURLFilter);
registrationBean.addUrlPatterns("/test/*");
registrationBean.setOrder(2); // set precedence
return registrationBean;
}
}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×