Easy learning with example program codes

Servlet filter in java

Servlet filter:

Servlet filters are the objects which are used to perform some filtering task. A filter can be applied to a servlet, jsp or html.

Servlet filters are mainly used for following tasks:

  1. Pre-processing: Servlet filter is used for pre-processing of request before it accesses any resource at server side.
  2. Post-processing: Servlet filter is used for post-processing of response before it sent back to client.

How to create a filter?

Implement javax.servlet.Filter interface to create a filter.

Filter interface:

To create a filter you have to implement filter interface. Filter interface is in javax.servlet package javax.servlet.Filter. It provides life cycle methods of a filter.

Methods of filter interface:

1. init(FilterConfig config): This method is used to initialize the filter. It is called only once by web container.

Syntax: public void init(FilterConfig config)

2. doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): This method is used for performing pre-processing and post-processing tasks. It is called every time for a request/response comes for a resource to which filter is mapped.

Syntax: public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)

3. destroy(): This method is called only once by the web container when filter is taken out of the service.

Syntax: public void destroy()

FilterChain interface:

FilterChain object is used to call the next filter or a resource if it is the last filter in filter chaining.

Method of FilterChain interface:

1. doFilter(HttpServletRequest request, HttpServletResponse response): This method is used to call the next filter in filter chaining.

Syntax: public void doFilter(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

How to define a filter in web.xml?

<filter> attribute is used to define a filter in web.xml.



//Other attributes.


<filter-name>filterName </filter-name>







//Other attributes.



import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
* This class is used as a filter.
* @author codesjava
public class LoginFilter implements Filter {
	private static final long serialVersionUID = 1L;
	public void init(FilterConfig filterConfig) 
		throws ServletException {
      public void doFilter(ServletRequest request, 
			ServletResponse response, FilterChain chain) 
	                throws IOException, ServletException {  
    	PrintWriter out = response.getWriter();
    	//get parameters from request object.
    	String userName = request.getParameter("userName").trim();
    	String password = request.getParameter("password").trim();
    	//check for null and empty values.
    	if(userName == null || userName.equals("") || 
    			password == null || password.equals("")){
    		out.print("Please enter both username " +
    				"and password. <br/><br/>");
    		RequestDispatcher requestDispatcher = 
    		requestDispatcher.include(request, response);
    	}//Check for valid username and password.
    	else if(userName.equals("jai") && password.equals("1234")){
    		 chain.doFilter(request, response);
    		out.print("Wrong username or password. <br/><br/>");
    		RequestDispatcher requestDispatcher = 
    		requestDispatcher.include(request, response);
    public void destroy() {

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 * This class is used to print login message 
 * if user logged in successfully.
public class WelcomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   //no-argument constructor
    public WelcomeServlet() {
    protected void doPost(HttpServletRequest request, 
		HttpServletResponse response)
	            throws ServletException, IOException {
        PrintWriter out = response.getWriter();  
        out.print("<h1>You are logged in successfully.</h1>");  


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<form action="WelcomeServlet" method="POST">
		Username:<input type="text" name="userName"/>
		Password:<input type="password" name="password"/>
		<input type="submit" value="login"/> 


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" 
id="WebApp_ID" version="2.5">


servlet example 14 login
Enter username: jai and password: 1234
servlet example 14 value
Click on login button.
servlet example 14 welcome
Download this example.
Next Topic: FilterConfig interface with example.
Previous Topic: HttpSession in servlet with example.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at


We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki