Java Servlet Filter


An object that is utilized both during pre- and post- processing phases of a request is a filter, input validation, server-side logging, authentication and permission, among other duties are frequently filtered using filters.

The entry is supplied in the web.xml file since the servlet is pluggable. The filter is automatically turned off if the item is removed from the web.xml file. In order to produce a filter, it has to implement javax.servlet. Servlets are extremely portable because they are built in the highly portable Java Language and follow a standard foundation. As a result, it makes it possible to develop sophisticated server extensions in operating systems and servers that are independent of one another

Why do we need a Servlet Filter?

We have many features of Servlet Filter. Some of them are mentioned below:

  • Logging on the Server

  • Log files record request parameter information

  • On the server, authentication and authorization

  • Compressing and decompressing of files

  • Both encryption and decryption are distinct process

  • Validation on the server

Advantages of Servlet Filter

Following are the features of Servlet Filter:

  • Can be plugged in

  • Filter is not reliant on a third-party resource

  • Requires little maintenance

  • Widely used

Servlet Filter Methods

It consists of 3 life cycle methods:

Method

Description

public void init(FilterConfig config) throws ServletException

To notify a filter that is being put into service, this activates the web container. It just requires the FilterConfig type or FilterConfig object as an argument

public void doFilters(ServletRequest request,ServletResponse response,FileterChain chain) throws ServletException,IOException

Every time a user makes a request for a resource that is mapped to the filter, the dofilter() method is invoked. It has filtering functions

public void destroy ()

This function is only ever called once, upon the removal of the filter from the service.

Example

In this illustration, we’ll create a webpage called index.html with a link that reads, “Click here.” Invoke the servlet “ServletFilter.java” by clicking the link however, the deployment descriptor- specified filter “MyFilter.java” that is connected with this Servlet will first be performed.

Index.html

Example

<html>
   <head>
      <title>HttpSession Event Listeners</title>
   </head>
   <body>
      <a href="ServletFilter">click here</a>
   </body>
</html>

ServletFilter.java

Example

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class ServletFilter extends HttpServlet {
   public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
         response.setContentType("text/html");
         PrintWriter out = response.getWriter();
         out.print(
            "<br>welcome to servlet filter example<br>");
      }
}

MyFilter.java

Example

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter {
   FilterConfig config;
   public void init(FilterConfig config)
      throws ServletException {
      this.config = config;
   }
   public void doFilter(ServletRequest req,
                        ServletResponse resp,
                        FilterChain chain)
   throws IOException, ServletException {
      PrintWriter out = resp.getWriter();
      String s = config.getInitParameter("construction");
      if (s.equals("yes")) {
         out.print("This page is under construction");
      } else {
         // sends request to next resource
         chain.doFilter(req, resp);
      }
   }
   public void destroy() {}
}

Web.xml

Example

<?xml version="1.0" encoding="UTF-8"?>
<web-app
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
   http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   id="WebApp_ID" version="4.0">
   <servlet>
      <servlet-name>ServletFilter</servlet-name>
      <servlet-class>ServletFilter</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>ServletFilter</servlet-name>
      <url-pattern>/ServletFilter</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>

Output

  • Step 1 − Click on “Click Here”

  • Step 2 − This message will pop up if you click on the following link

Conclusion

Within the realm of request processing, filters are essential components that serve important roles both before and after requests are handled. Importantly, filters enjoy widespread use for a variety of tasks including but not limited to validating inputs from users; logging server-side activities; providing authentication or authorization services. In the context of servlet technology specifically- since it is pluggable- filters can gracefully be introduced via appropriately configuring the web.xml file. If it becomes necessary for any reason to quickly disable an item on this file that happens to relate with such filters, removal will have exactly that effect immediately. In order for a developer to create a filter within this technology framework as well as enjoy its portability benefits among varied situations with different server environments; javavax.servlet implementation is crucial as its sole building block. It goes without saying that unlike other comparable technologies which have some degree of limitations regarding compatibility issues owing perhaps on account of programming languages differences etc.. The portable nature inherent in servlets make them perfect for deploying complex server extensions across diverse platforms irrespective of type.

Updated on: 01-Aug-2023

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements