Thursday, 17 April 2014

Servlets Filter Lifecycle

🚀 Master Java & Boost Your Coding Skills!

Subscribe to Ram N Java for crystal-clear programming tutorials and step-by-step guides.

🔔 Subscribe Now

Introduction to Servlet Filter Lifecycle

In Java web applications, a Filter is an object that transforms the header and content of requests and responses. The entire lifecycle of a filter is managed directly by the Servlet Container (such as Apache Tomcat) from the moment the application is deployed until the server shuts down.

The 3 Major Phases of Filter Lifecycle

1. Filter Loading & Initialization (init() Method)

When the web application starts or deploys, the servlet container loads the filter class, creates its instance, and calls the init(FilterConfig config) method.

  • The init() method is called only once in the filter's lifetime.
  • Once initialized, the filter is placed into active service.

2. Request Filtering (doFilter() Method)

Whenever a matching client request comes in for a targeted servlet or URL pattern, the servlet container invokes the doFilter() method.

  • The doFilter() method is called multiple times (once for every matching request/response).
  • This is where you perform tasks like request preprocessing, logging, authentication, and forwarding along the FilterChain.

3. Filter Destruction (destroy() Method)

When the filter is taken out of service (such as when the web application is undeployed or the server is shut down), the servlet container calls the destroy() method.

  • The destroy() method is executed only once.
  • Use this method to release resources, close database connections, or perform necessary cleanup operations.

Summary Flow

Filter Class Loaded → Instance Created → init() [Once] → doFilter() [Multiple Times] → destroy() [Once]

Recommended Related Tutorials

No comments:

Post a Comment

Tutorials