doFilter called twice, intended behaviour?

后端 未结 8 1639
孤街浪徒
孤街浪徒 2021-02-19 16:42

I\'m working through the Java EE servlet tutorial and tried the mood example. I noticed the doFilter is getting called twice, once the servlet call is in the chain and the secon

8条回答
  •  情话喂你
    2021-02-19 17:03

    The reason why the filter is called twice are the images used in the response creation, as for instance

    out.println("\"Duke
    ");

    Please see the log output

    2016-01-16T11:25:34.894+0100|Info: TimeOfDay doFilter method before sending to chain
    
    2016-01-16T11:25:34.895+0100|Info: MoodServlet get method called
    
    2016-01-16T11:25:34.895+0100|Info: TimeOfDay doFilter method after sending to chain
    
    2016-01-16T11:25:34.942+0100|Info: TimeOfDay doFilter method before sending to chain
    
    2016-01-16T11:25:34.942+0100|Info: TimeOfDay doFilter method after sending to chain
    

    src in img tag is nothing else than the second request for server to take care of. Please notice the url pattern used in the @WebFilter

    @WebFilter(filterName = "TimeOfDayFilter",
    urlPatterns = {"/*"},
    initParams = {
        @WebInitParam(name = "mood", value = "awake")})
    

    It will intercept all the requests coming into mood application. As an exercise simply try to remove images from the response or change url pattern to intercept only requests ending up in MoodServlet

    @WebFilter(filterName = "TimeOfDayFilter",
    urlPatterns = {"/report"},
    initParams = {
        @WebInitParam(name = "mood", value = "awake")})
    

    Both will result in one call of doFilter as you originally expected

    2016-01-16T11:28:53.485+0100|Info: TimeOfDay doFilter method before sending to chain
    
    2016-01-16T11:28:53.486+0100|Info: MoodServlet get method called
    
    2016-01-16T11:28:53.487+0100|Info: TimeOfDay doFilter method after sending to chain
    

提交回复
热议问题