I'm having a problem I do not see reference to anywhere on SO. I have a spring @Configuration class that looks like this:
package com.mypackage.admin.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class ApiFilterConfig {
@Bean
public FilterRegistrationBean<RequestFilter> filterRegistrationBean2() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean <RequestFilter> registrationBean = new FilterRegistrationBean(new CorsFilter(source));
return registrationBean;
}
@Bean
public FilterRegistrationBean<RequestFilter> filterRegistrationBean() {
FilterRegistrationBean <RequestFilter> registrationBean = new FilterRegistrationBean();
RequestFilter customURLFilter = new RequestFilter();
registrationBean.setFilter(customURLFilter);
registrationBean.addUrlPatterns("/mobile");
registrationBean.addUrlPatterns("/team");
registrationBean.addUrlPatterns("/team/delete");
registrationBean.addUrlPatterns("/user/*");
return registrationBean;
}
}
And a filter that looks like this:
public class RequestFilter implements Filter {
//TODO: Needs integration test
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
System.out.println("hi");
}
}
These components appear to be wired up partially correct because the Cors configuration works and the filter is applied to the designated URL patterns. However, the actual API method is not called. I do print statements and set debug points in that method and nothing happens when calling the endpoint. I check the database and nothing persists. Its like the request is just dropped after it goes through the filter and prints "hi". What am I doing wrong? How do I make the filter process the request and also allow the API method invocation to continue?
CodePudding user response:
You lack the important function: chain.doFilter(request,response);
Without above function the chain will be broken.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
System.out.println("hi");
chain.doFilter(request,response);
}
https://docs.oracle.com/javaee/7/api/javax/servlet/FilterChain.html