doFilter调用了两次,预期的行为? [英] doFilter called twice, intended behaviour?

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

问题描述

我正在研究Java EE servlet教程,并尝试了心情示例 .我注意到,一旦Servlet调用在链中,而第二次没有,则doFilter被调用两次.

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 second time it isnt.

我在TimeOfDayFilter.java和MoodServlet.java中添加了一些printlns来显示这一点.

I added some printlns in the TimeOfDayFilter.java and in the MoodServlet.java to show this.

TimeOfDayFilter.java:

TimeOfDayFilter.java:

    ...
    System.out.println("TimeOfDay before"); //added
    chain.doFilter(req, res);
    System.out.println("TimeOfDay after"); //added
    ...

MoodServlet.java:

MoodServlet.java:

    ...
    response.setContentType("text/html;charset=UTF-8");

    System.out.println("MoodServlet"); //added

    PrintWriter out = response.getWriter();
    ...

在调用servlet时,来自glassfish服务器(3.1)窗口的结果如下:

The result from the glassfish server (3.1) window when calling the servlet is the following:

    INFO: mood was successfully deployed in 406 milliseconds.
    INFO: TimeOfDay before
    INFO: MoodServlet
    INFO: TimeOfDay after
    INFO: TimeOfDay before
    INFO: TimeOfDay after

这是预期的行为吗?如果是这样,那么额外通话的原因是什么?

Is this intended behaviour? If so, what is the reason for the extra call?

推荐答案

chain.doFilter(request,response);

这会将控制权传递给与过滤器关联的servlet. 但是,在执行了相应的servlet之后,控件将返回到上一行的末尾,然后执行当前doFilter()中的所有行.

This will pass the control to the servlet the filter is associated with. But after the corresponding servlet is executed, the control comes back at the end of the above line and all the lines thereafter in the current doFilter() is executed.

如果您想将控件永久传递给servlet而不让它返回过滤器,只需添加

If you want to pass the control permanently to the servlet and not letting it return to the filter, just add a

return;

在当前过滤器的chain.doFilter(request,response)行的末尾.

at the end of chain.doFilter(request,response) line in the current filter.

这篇关于doFilter调用了两次,预期的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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