Monday 9 September 2019

How to add a filter to spring boot application?


Step 1: Create a filter by implementing Filter interface.
@Component
public class PerformanceFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(PerformanceFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long time1 = System.nanoTime();
        chain.doFilter(request, response);
        long time2 = System.nanoTime();

        logger.info("Total time taken: {} nano seconds", (time2 - time1));

    }

}

Make sure you added spring annotation @Component.


Step 2: Create a bean of type 'FilterRegistrationBean'.
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<PerformanceFilter> perfFilter() {
        FilterRegistrationBean<PerformanceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new PerformanceFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }
}

As you see above snippet, I applied PerformanceFilter on all url patterns.

Find the below working application.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}


FilterConfig.java
package com.sample.app.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sample.app.filter.PerformanceFilter;

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<PerformanceFilter> perfFilter() {
        FilterRegistrationBean<PerformanceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new PerformanceFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }
}


HomeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @RequestMapping("/")
    public String homePage() {
        return "Welcome to Spring boot Application Development";
    }

}


PerformanceFilter.java
package com.sample.app.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PerformanceFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(PerformanceFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long time1 = System.nanoTime();
        chain.doFilter(request, response);
        long time2 = System.nanoTime();

        logger.info("Total time taken: {} nano seconds", (time2 - time1));

    }

}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>springbootMisc</groupId>
    <artifactId>springbootMisc</artifactId>
    <version>1</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <packaging>jar</packaging>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

</project>


Total project structure looks like below.

Run App.java.

Open the url ‘http://localhost:8080/’ in browser. You can see below kind of message in console.

2019-07-19 12:05:59.462  INFO 41560 --- [nio-8080-exec-1] com.sample.app.filter.PerformanceFilter  : Total time taken: 34703886 nano seconds

You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment