-1

Trying to add a very simple filter to my Spring-web-project, I've noticed that *all examples are using the web.xml file that is not available when choosing a web project on Spring.

Could someone write a complete starter set for a super simple filter? just printing here in all filter states is enough. I'll pick it up from there to checking session data.

any help/good reference is welcomed. thanks

Yaniv Peretz
  • 1,118
  • 2
  • 13
  • 22
  • 1
    Just to be sure, do you use plain Spring or Spring Boot? – helospark Nov 30 '17 at 18:59
  • Dependency spring-boot. – Yaniv Peretz Nov 30 '17 at 19:09
  • There are about 10 answers there, without a verified answer. each solving in a different way, could you point out to any of the specific answers? I cannot seem to get the complete picture of the relevant setting. – Yaniv Peretz Nov 30 '17 at 19:29
  • All of the solutions work, they are just different way of solving the problem. I prefer the FilterRegistrationBean method of registering filters. I have posted it as an answer. – helospark Nov 30 '17 at 19:44

1 Answers1

0

There are multiple solutions to create a filter in your Spring Boot application. See the following question for multiple options: How to add a filter class in Spring Boot?

I prefer creating a FilterRegistrationBean in my application context, it can have similar configuration then the config you would write to web.xml using plain Spring MVC.

From the above question registering a filter can be done as follows:

@Bean
public FilterRegistrationBean someFilterRegistration() {

   FilterRegistrationBean registration = new FilterRegistrationBean();
   registration.setFilter(someFilter());
   registration.addUrlPatterns("/url/*");
   registration.addInitParameter("paramName", "paramValue");
   registration.setName("someFilter");
   registration.setOrder(1);
   return registration;
} 

public Filter someFilter() {
   return new SomeFilter();
}

If you need multiple filters, just create a bean for each.

Spring Boot will automatically find these beans, and configure the filters for you.

helospark
  • 1,420
  • 9
  • 12