views:

37

answers:

3

Hi Filters are like servlets but managed by the web container but there is service() method in servlets but there is no method called service in filters. There are three only three methods init(), doFilter(), and destroy().Can anybody elaborate on this ?

+3  A: 

The doFilter() method is the one that is called whenever a Filter processes a request.

A simple example is as follows:

public void doFilter(ServletRequest request,
  ServletResponse response, FilterChain chain) 
  throws IOException, ServletException {
  // .. pre filter logic
  chain.doFilter(request, response);
  // .. post filter logic
}

The filter allows you to decide whether to continue processing the request i.e. whether subsequent filters will process this request and finally the servlet at the end. You can choose not to call chain.doFilter (good example of this would be if you're using the filter for authentication). See this guide for more information.

jamie mccrindle
+1 for the example. Only too bad that you initially pointed a 10 years old tutorial. True, the filters have not changed much in years, but the remnant of the tutorial may give misinformation. I edited the most recent version in.
BalusC
Thanks for the edit. Filters are like the sharks of Java world, millions of years old but still good at what they do.
jamie mccrindle
+2  A: 

A filter serves a different role from a servlet. Therefore it doesn't have the same methods. A filter's role is, well, to filter, and that's what the doFilter() method does.

Have a look at the "Filtering Requests and Responses" chapter of the Java EE Tutorial.

Eli Acherkan
A: 

For more details, in addition to the other responses, see page 49 of the Java Servlet Specification 2.4 at https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_JCP-Site/en_US/-/USD/ViewFilteredProducts-SimpleBundleDownload

Confusion