Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why spring boot filter call twice?

my spring boot version is 1.5.4,here is my config code

@SpringBootApplication
@Configuration
@RestController
@ServletComponentScan
public class Application {

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

    @RequestMapping("/")
    public String home() {
        System.out.println("test");
        return "Hello World!";
    }

}

here is my servlet filter code

@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {


@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    System.out.println("LogFilter");
    chain.doFilter(request, response);
}

//init and destroy

When i visit http://localhost:8080/ console is out print

LogFilter
test
LogFilter <----the second time

why call filter twice?Spring boot Why do this? Is there a relevant document or source reference?where I want him to call once, how can i do it?

update: thx all the problem has been solved

like image 955
Nestle Caau Avatar asked Apr 13 '26 12:04

Nestle Caau


2 Answers

Please check if the class where in you had defined your filter was a bean or a regular class. In case it is a bean/component then you do not have to specifically register the filter in your security configuration for eg by using

http.addFilterBefore(new YourFilter(), BasicAuthenticationFilter.class). 

By registering a bean additionally as mentioned, the same filter will get executed twice.

like image 105
wrathtoliar Avatar answered Apr 15 '26 01:04

wrathtoliar


If you try to log the request url from doFilter method, you'll see why. Here is I create new SpringBoot project and test with doFilter method.

    @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    logger.info(request.getRequestURL().toString());
    filterChain.doFilter(servletRequest,servletResponse);
}

Well, the two urls are

http://localhost:8080/index
http://localhost:8080/favicon.ico
like image 21
Yongzhao Zhang Avatar answered Apr 15 '26 02:04

Yongzhao Zhang