javascript
Brief description  about Online courses   join in Online courses
OR

Servlet Filters

Chinmay  Hegde
Chinmay Hegde
JAVA/ J2EE Developer

Servlet Filters are the latest components that are added in Servlet 2.3 specifications. These filters are used basically for intercepting and modifying requests and response from server.  Consider a scenario where you want to check session from the every users request and if it is valid then only you want to let the user access the page. You can acheive this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter.

A filter offers a useful way of performing filtered functionality in a JavaSW web application. Typically, filters do not generate content themselves, although in this example, the filter will generate some minimal content to show how it is called. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

A filter is typically used to perform a particular piece of functionality either before or after the primary functionality of a web application is performed. As an example, if a request is made for a particular resource such as a servletW and a filter is used, the filter code may execute and then pass the user on to the servlet. As a further example, the filter might determine that the user does not have permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Filters are Java components very similar to Servlets – which you can use to intercept request and process requests before they are sent to the servlet, or to process responses after the servlet has completed, but before the response goes back to the client

The container decides when to execute the filters depending upon their configuration in Deployment Descriptor or web.xml. In the DD, the deployer maps which filter will be called for which request URL patterns. So it’s the deployer not the programmer, who decides which subset of requests or response, should be processed by filters.

What can you do with Filters?

Request Filters
• Perform security checks
• Reformat request headers or bodies
• Audit or log requests

Response Filters
• Compress the response stream
• Append or alter the response stream
• Create a different response altogether

Filters are executed in chain and the same filter can be used as both request and response filter.

Write your comment now