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:

  • index.html
  • MyFilter.java
  • AdminServlet.java
  • web.xml

index.html

Name:
Password:

MyFilter.java

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.*;  
  
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=resp.getWriter();  
          
    String password=req.getParameter("password");  
    if(password.equals("admin")){  
    chain.doFilter(req, resp);//sends request to next resource  
    }  
    else{  
    out.print("username or password error!");  
    RequestDispatcher rd=req.getRequestDispatcher("index.html");  
    rd.include(req, resp);  
    }  
          
}  
    public void destroy() {}  
  
}

AdminServlet.java

import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
  
public class AdminServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        out.print("welcome ADMIN");  
        out.close();  
    }  
}

web.xml

  
   
    AdminServlet  
    AdminServlet  
    
  
    
    AdminServlet  
    /servlet1  
    
    
   
  f1  
  MyFilter  
    
    
  f1  
  /servlet1