Home > Java > javaTutorial > Why is My Spring Filter Being Invoked Twice, and How Can I Fix It?

Why is My Spring Filter Being Invoked Twice, and How Can I Fix It?

Mary-Kate Olsen
Release: 2024-12-09 03:00:15
Original
975 people have browsed it

Why is My Spring Filter Being Invoked Twice, and How Can I Fix It?

Filter Registered Twice with Spring Bean Annotation

When registering a filter as a Spring bean, it is important to consider the potential for multiple invocations. In certain scenarios, the filter may be triggered twice, as observed in the following issue:

Issue:

A user defines a filter, A, which extends Spring's GenericFilterBean. When this filter is registered as a bean in the Spring Security configuration, an additional invocation is observed, resulting in the following output:

filter A before
filter A before
mycontroller invoke
filter A after
filter A after
Copy after login

Query:

Why is the filter being called twice, and how can this issue be resolved?

Answer:

The extra invocation occurs because Spring Boot automatically registers any bean of type Filter with the servlet container. To prevent this, there are two options:

Option 1: Register Filter with Spring Security Only

Avoid exposing the filter as a bean and register it solely with Spring Security, as follows:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(new A(), BasicAuthenticationFilter.class);
    http.csrf().disable();
}
Copy after login

Option 2: Use FilterRegistrationBean with Annotation

If autowiring dependencies into the filter is necessary, one can register it as a bean but disable its automatic registration with the servlet container using a FilterRegistrationBean:

@Bean
public FilterRegistrationBean registration(MyFilter filter) {
    FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<MyFilter>(filter);
    registration.setEnabled(false);
    return registration;
}
Copy after login

The above is the detailed content of Why is My Spring Filter Being Invoked Twice, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template