Spring Boot with Filter by URL Pattern – Example

You just want to see an minimal example of Spring boot with Filter by URL Pattern (or with Servlet Filter).

This page is for you.

This example is a part of  Spring Boot with all examples

Full Code with Spring Boot 1.5.8.RELEASE:

4_spring-boot-filter-urlpattern.zip

What you need for run this:

  • Maven 3
  • Java 8

What the code will do:

  • Call an url  then a filter in the service will capture the request.

Explain:

This is the file structure:

For pom.xml,  TestRestController.java,  . They are the same as explain in here REST with Spring Boot , so I will not explain them.

In ExampleFilter.java, this filter will just print a message to console where there is request to /api/count, the code looks like this:

package com.surasint.example.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.FilterChain;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/count")
public class ExampleFilter implements Filter{
    private static final Logger logger = LoggerFactory.getLogger(ExampleFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("filter:"+ ((HttpServletRequest)servletRequest).getRequestURL());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

he keys here are :

  • Line 7 : import javax.servlet.Filter
  • Line 17 :  implment Filter
  • Line 16 : use WebFilter(urlPatterns = “/api/count”) to let Sping know it exists. Note that WebFilter is not from Spring, it is from Servlet 3.

Not done yet, we have to config our Sping Boot Application to know that it has a Servlet annotation, in MyApplication.java :

package com.surasint.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@ServletComponentScan
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {

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

}

This key is:

  • Line 8: @ServletComponentScan tells the Spring Boot to scan to find such @WebFilter annotation.

Try:

run this in console:

mvn clean package

Then run this to start:

mvn clean spring-boot:run

You should see something like this:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

.....
.....
2017-12-12 22:03:04.243  INFO 260 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotation
ConfigEmbeddedWebApplicationContext@7595f8d7: startup date [Tue Dec 12 22:03:01 CET 2017]; root of context hierarchy

Open a browswer and try to go to this url:

http://localhost:8080/api/count

In the console, you should see this:

2017-12-16 11:10:16.355  INFO 9876 --- [nio-8080-exec-1] c.s.example.web.filter.ExampleFilter     : filter:http://localhost:8080/api/count

But if you call this url:

http://localhost:8080/api/count2

You will see NO message in console.