为什么spring boot过滤器调用两次? [英] why spring boot filter call twice?

查看:36
本文介绍了为什么spring boot过滤器调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 spring boot 版本是 1.5.4,这是我的配置代码

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!";
    }

}

这是我的 servlet 过滤器代码

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

当我访问 http://localhost:8080/ 控制台打印出来

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

LogFilter
test
LogFilter <----the second time

为什么要调用过滤器两次?Spring boot 为什么要这样做?有相关的文档或者源码参考吗?我要他打一次电话,怎么办?

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

推荐答案

如果您尝试从 doFilter 方法记录请求 url,您就会明白原因.这是我创建新的 SpringBoot 项目并使用 doFilter 方法进行测试.

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);
}

好吧,这两个网址是

http://localhost:8080/index
http://localhost:8080/favicon.ico

这篇关于为什么spring boot过滤器调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆