Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How the filter know it is before- and after-request processing?

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the filter know it is before- and after-request processing?

actually it is a simple filter to record the processing time. But I am wondering how the servlet container know it is before or after ?

Let me say, the filter is applied to /test.jsp. when users click www.root/test.jsp, container will route the request to this filter. After finishing , it will go to next filter with chain.doFilter(..). If this is the last filter, then container will go to /test.jsp.

But , after service of /test.jsp, how the container will route the response back to this filter? if going back to this filter, how they will skip chain.doFilter(..) to the ending part of coding ?

Thanks.

------------------------------
public void doFilter(...){
long before = System.currentTimeMillis();
chain.doFilter(request, response);
long after = System.currentTimeMillis();

String name = "";
if (request instanceof HttpServletRequest) {
name = ((HttpServletRequest)request).getRequestURI();
}
config.getServletContext().log(name + ": " + (after - before) + "ms");
}
 
Ken Robinson
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two things.

Tresource (Servlet, JSP, HTML) of the current URL is alwasy in the 'middle' of the chain. Filters always go from first to last, then last to first. The first <filter-mapping> in web.xml (from top to bottom) that matches the URL is first.

The key to before or after is the chain.doFilter(request,response) call.
All code before this is the before logic. All code after this is the after logic. The call to the chain.doFilter is how you go to the next 'link' in the chain. When the 'middle' is reached you start returning to all Filters that are in the chain, which is why 'on the way back' the last if first, the first is last.

If you have:
A Filter (F1) mapped to x.html,
A Filter (F2) mapped to x.html
and something (Servlet, JSP) mapped to x.html
you will get...

F1 before doFilter
F2 before doFilter
Mapped resource (Servlet, JSP)
F2 after doFilter
F1 after doFilter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic