Open In App

Java Servlets | Need of Filters

The need for implementing filters can be understood with the help of few examples Let’s take example of a Web application that formats the data to be presented to clients in a specific format say Excel However, at a later point of time, the clients may require data in some other format, such as Hypertext Markup Language (HTML) Portable Document Format (PDF), or Word. In such a situation instead of modifying the code every time to change the format of data, a filter can be created to transform data dynamically in the required formats.

Let’s consider another example where a developer creates a Web application in which a servlet handles user logins. This implies that when a user submits his credentials, the servlet verifies the credentials against the user information. The servlet also creates a session for the user, so the other components in the application can also use the session details of the user. At a later point of time, the developer might require maintaining a login entry for each user login attempt in the application server’s log system. In order to implement this, the developer would need to change the existing code or add additional code to the servlet and redeploy the Web application.



In such a situation, a servlet, besides fulfilling its primary objective that is to accept request and send responses to clients has to implement additional functionalities. This additional lo servlet reduces the efficiency of the application. To overcome this problem filters were introduced that can implement these additional functionalities, such as verifying login credentials maintaining the server log in a database. One of the most striking features of the filters is that they can be reused in other Web applications as well.

Some situations and tasks where filters can be used are as follows:



Elaboration of some situation where filters are needed:

Article Tags :