Servlet Filter
next>> <<prev
A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption
and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the [Link] file, if we remove the entry
of filter from the [Link] file, filter will be removed automatically and we don't need to change the
servlet.
So maintenance cost will be less.
Note: Unlike Servlet, One filter doesn't have dependency on another filter.
Usage of Filter
recording all incoming requests
logs the IP addresses of the computers from which the requests originate
conversion
data compression
encryption and decryption
input validation etc.
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Filter API
Like servlet filter have its own API. The [Link] package contains the three interfaces of Filter
API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life
cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used
to initialize the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when
request,HttpServletResponse response, user request to any resource, to which the
FilterChain chain) filter is [Link] is used to perform filtering
tasks.
public void destroy() This is invoked only once when filter is taken
out of the service.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the [Link] object
is passed in the doFilter method of Filter [Link] FilterChain interface contains only one
method:
1. public void doFilter(HttpServletRequest request, HttpServletResponse response):
it passes the control to the next filter or resource.
How to define Filter
We can define filter same as servlet. Let's see the elements of filter and filter-mapping.
1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an
advantage over servlet-name element i.e. it can be applied on servlet, JSP or HTML.
Simple Example of Filter
In this example, we are simply displaying information that filter is invoked automatically after the
post processing of the request.
[Link]
[Link]
1. import [Link];
2. import [Link];
3.
4. import [Link].*;
5.
6. public class MyFilter implements Filter{
7.
8. public void init(FilterConfig arg0) throws ServletException {}
9.
10. public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=[Link]();
14. [Link]("filter is invoked before");
15.
16. [Link](req, resp);//sends request to next resource
17.
18. [Link]("filter is invoked after");
19. }
20. public void destroy() {}
21. }
[Link]
1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link].*;
6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. [Link]("<br>welcome to servlet<br>");
15.
16. }
17.
18. }
[Link]
For defining the filter, filter element of web-app must be defined just like servlet.
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. </filter>
17.
18. <filter-mapping>
19. <filter-name>f1</filter-name>
20. <url-pattern>/servlet1</url-pattern>
21. </filter-mapping>
22.
23.
24. </web-app>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)
Next TopicAuthentication Filter
Authentication Filter
We can perform authentication in filter. Here, we are going to check to password given by the user
in filter class, if given password is admin, it will forward the request to the WelcomeAdmin servlet
otherwise it will display error message.
Example of authenticating user using filter
Let's see the simple example of authenticating user using filter.
Here, we have created 4 files:
[Link]
[Link]
[Link]
[Link]
[Link]
<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="login">
</form>
[Link]
import [Link];
import [Link];
import [Link].*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=[Link]();
String password=[Link]("password");
if([Link]("admin")){
[Link](req, resp);//sends request to next resource
}
else{
[Link]("username or password error!");
RequestDispatcher rd=[Link]("[Link]");
[Link](req, resp);
}
}
public void destroy() {}
[Link]
import [Link];
import [Link];
import [Link];
import [Link].*;
public class AdminServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("welcome ADMIN");
[Link]();
}
}
[Link]
<web-app>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)
<<Prev Next>>
FilterConfig
An object of FilterConfig is created by the web container. This object can be used to get the
configuration information from the [Link] file.
Methods of FilterConfig interface
There are following 4 methods in the FilterConfig interface.
1. public void init(FilterConfig config): init() method is invoked only once it is used to
initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value
for the specified parameter name.
3. public [Link] getInitParameterNames(): Returns an enumeration
containing all the parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.
Example of FilterConfig
In this example, if you change the param-value to no, request will be forwarded to the servlet
otherwise filter will create the response with the message: this page is underprocessing. Let's see
the simple example of FilterConfig. Here, we have created 4 files:
[Link]
[Link]
[Link]
[Link]
[Link]
<a href="servlet1">click here</a>
[Link]
import [Link];
import [Link];
import [Link].*;
public class MyFilter implements Filter{
FilterConfig config;
public void init(FilterConfig config) throws ServletException {
[Link]=config;
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=[Link]();
String s=[Link]("construction");
if([Link]("yes")){
[Link]("This page is under construction");
}
else{
[Link](req, resp);//sends request to next resource
}
}
public void destroy() {}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link].*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<br>welcome to servlet<br>");
[Link]
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>construction</param-name>
<param-value>no</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)
<<Prev Next>>
For Videos Join Our Youtube Channel: Join Now
Feedback
Send your Feedback to feedback@[Link]
Useful Filter Examples
There is given some useful examples of filter.
Example of sending response by filter only
[Link]
import [Link].*;
import [Link].*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=[Link]();
[Link]("<br/>this site is underconstruction..");
[Link]();
}
public void destroy() {}
}
Example of counting number of visitors for a single page
[Link]
import [Link].*;
import [Link].*;
public class MyFilter implements Filter{
static int count=0;
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=[Link]();
[Link](request,response);
[Link]("<br/>Total visitors "+(++count));
[Link]();
}
public void destroy() {}
}
Example of checking total response time in filter
[Link]
import [Link].*;
import [Link].*;
public class MyFilter implements Filter{
static int count=0;
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=[Link]();
long before=[Link]();
[Link](request,response);
long after=[Link]();
[Link]("<br/>Total response time "+(after-before)+" miliseconds");
[Link]();
}
public void destroy() {}
}
<<Prev Next>>
For Videos Join Our Youtube Channel: Join Now
Feedback
Send your Feedback to feedback@[Link]
Help Others, Please Share
Student Loans up to
$100k. Get the
Funding You Need for Apply Now
Your STEM Degree
from MPOWER
MPOWER Financing