So actually why we are using this ? What is that much of important in filters ? Here is the answer..
Suppose you want to enhance your web app by tracking the users that goes to particular servlet. So the typical answer is change the code in servlet and add necessarily things to fulfill the requirement. This is not a good choice. Because editing the servlet source code can effect on the other areas in your app. So the one and only choice is to use Filters.
In this article you will learn some basic things about filters and specially how to use filters.
Filters can be chained together, to run one after the other and its in-dependable. Filters don't know what filter before run or after.
Our Deployment Descriptor(web.xml) control the order that filters run.
Filter's Life Cycle
Every Filter Must implement 3 methods.
1. init()
- Can do any set-up task before the filter called.
- This method is called every time the container determines that the filter should be applied to the current request.
- It takes 3 args.--> ServletRequest, ServletResponse, FilterChain
- This is the method that implements all of your logic that you want to do in filter.
3. destroy()
- Container decide to remove the filter it calls the destroy().
- Can do any clean-up
When we config filters in web.xml we usually do 3 things.
1.Filter Declare
<filter>
<filter-name>name of the filter</filter-name>
<filter-class>class that contain filter login (ex: implement Filter interface)</filter-class>
<init-param>
<param-name>para name</param-name>
<param-value>para value</param-value>
</init-param>
</filter>
- <filter-name> and <filter-class> are mandatory
2. Map Filter to URL
<filter-mapping>
<filter-name>
name of the filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.Map to Servlet Name
<filter-mapping>
<filter-name>name of the filter
</filter-name><servlet-name>name of the servlet map name</servlet-name>
</filter-mapping>
- If the request coming from forward, include , request dispatch or error you can use this.
- <dispatcher>FORWARD</dispatcher> or ... inside 2 nd option.
Here is some basic things about request filter. On next post I will talk about response filters and some basic example of this implementation. KIT :)
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteJava Training in Chennai Java Training in Chennai | Core Java Training in Chennai
Online Java Training Online Java Training | Java J2EE Online Training | JavaEE Training Institute in Chennai
Java Training in Chennai
ReplyDeleteOnline MVC Training India | Angularjs Training | Java Training in Chennai |
Java Training in CHennai | Java Training in CHennai