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:

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 :

This key is:

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

Try:

run this in console:

Then run this to start:

You should see something like this:

Open a browswer and try to go to this url:

In the console, you should see this:

But if you call this url:

You will see NO message in console.