Open In App

Servlet – Authentication Filter

Last Updated : 16 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.

Authentication Filter In Servlets 

Authentication may be done in the filter. Here, we’ll verify the user’s password in the ServletFilter class; if the password is “geeksforgeeks”, the request will be sent to the Gfg servlet; otherwise, an error message will be displayed.

Implementation: Let’s look at a simple example of utilizing a filter to authenticate a user. We’ve produced four files here:

  • index.html
  • Gfg.java
  • ServletFilter.java
  • web.xml

File: index.html

HTML




<form action = "servlet1">
  
               Name: < input type = "text" name = "name" / > < br / > < br / >
  
                                    Password: < input type = "password" name = "password" / > < br / > < br / >
  
                                            <input type = "submit" value = "login">
  
                                                    < / form >


Example 1-A:

Java




// Java Program to Illustrate ServletFilter Class
  
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
  
// Class
// Implementing Filter class
public class ServletFilter 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("geeksforgeeks")) {
  
            // Sending request to next
            chain.doFilter(req, resp);
        }
  
        // Password incorrect
        else {
            out.print("username or password is wrong");
            RequestDispatcher rd
                = req.getRequestDispatcher("index.html");
            rd.include(req, resp);
        }
    }
    public void destroy() {}
}


Example 1-B:

Java




// Java Program to Illustrate GFG Class
  
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
// Class
// Derived from HttpServlet class
public class GFG extends HttpServlet {
  
    // Getting request response
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
  
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
  
        out.print("welcome to GEEKSFORGEEKS");
  
        // Closing connections to
        // avoid any memory leakage
        out.close();
    }
}


File: web.xml

XML




<web-app>  
 <servlet>  
    <servlet-name>Gfg</servlet-name>  
    <servlet-class>Gfg</servlet-class>  
  </servlet>  
    
  <servlet-mapping>  
    <servlet-name>Gfg</servlet-name>  
    <url-pattern>/servlet1</url-pattern>  
  </servlet-mapping>  
      
 <filter>  
  <filter-name>f1</filter-name>  
  <filter-class>ServletFilter</filter-class>  
  </filter>  
  <filter-mapping>  
  <filter-name>f1</filter-name>  
  <url-pattern>/servlet1</url-pattern>  
  </filter-mapping>  
      
</web-app>


Output:

Click on the login button, if the password is correct then the above message will be shown to the user.



Similar Reads

Servlet - Filter
A filter is an object that is used throughout the pre-and post-processing stages of a request. Filters are mostly used for filtering tasks such as server-side logging, authentication, and authorization, input validation, and so on. The servlet is pluggable, which means that the entry is specified in the web.xml file. If the entry is deleted from th
3 min read
Java Servlet Filter with Example
A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server, i.e., before and after the execution of a servlet for filtering the request. Filter API (or interface) includes some methods which help us in filtering requests. To understand the concept of Filters, first, you should have an understanding of t
4 min read
Java Servlet Filter
Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below Instantiate.Initialize.Filter.destroy. These stages are similar to a servlet's Instantiate, Initialize, Filter, destroy. The f
4 min read
Spring Boot - Servlet Filter
Spring boot Servlet Filter is a component used to intercept &amp; manipulate HTTP requests and responses. Servlet filters help in performing pre-processing &amp; post-processing tasks such as: Logging and Auditing: Logging operations can be performed by the servlet filter logging the request and response which assists in debugging and troubleshooti
8 min read
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
What is Servlet Collaboration? The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations. What are the principle ways provided by Java to achieve Servlet Collaboration?The servlet api provides tw
4 min read
Starting with first Servlet Application
To get started with Servlets, let's first start with a simple Servlet application i.e LifeCycle application, that will demonstrate the implementation of the init(), service() and destroy() methods.First of all it is important to understand that if we are developing any Servlet application, it will handle some client's request so, whenever we talk a
3 min read
Life Cycle of a Servlet
The entire life cycle of a Servlet is managed by the Servlet container which uses the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before creating a Servlet object, let's first understand the life cycle of the Servlet object which is actually understanding how the Servlet container manages the Servlet object.
9 min read
Difference between Servlet and JSP
Brief Introduction: Servlet technology is used to create a web application. A servlet is a Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response model. Servlets are mainly used to extend the applications hosted by web services. JSP is used to create web applications just like Se
3 min read
URL Rewriting using Java Servlet
Url rewriting is a process of appending or modifying any url structure while loading a page. The request made by client is always a new request and the server can not identify whether the current request is send by a new client or the previous same client. Due to This property of HTTP protocol and Web Servers are called stateless. But many times we
5 min read
Hidden Form Field using Annotation | Java Servlet
Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. The main advantage of using Hidden form field that i
4 min read
Article Tags :
Practice Tags :