Need of Filters in Java Servlet


In order to ensure that requests are properly handled, developers often use filters to prepare, and post-process them. These objects can perform all sorts of useful operations such as input validation, conversion, logging, compression, encryption, and decryption.

What's particularly great about servlet filters is how easy they are to manipulate: as pluggable entities defined by the web.xml file, removing or adjusting filters is as simple as deleting an entry from the code base. This streamlined process means lower costs for maintenance.

Usage of Filter

The validation of data becomes critical when it holds inherent importance in business operations. It is important to verify the information coming from clients for storing it in a database via the server, as invalid data can have disastrous effects on the system’s functionality. Although filters can be added client-side, javascript disabled on the client-side will not examine requests or data, which makes server-side filters a necessity.

Following are some major usages of Filter in Java Servlet

  • Recording all the incoming requests

  • Conversion

  • Data compression

  • Input validation

  • Encryption and Decryption

Advantage of Filters in Java Servlet

  • Authenticate and authorize resource requests. Confirming the user's authenticity prior to forwarding their request.

  • To deliver it to the servlet, format either the request body or header. The raw data needs preparation.

  • Client-sent response data will be compressed. (Example: encryption)

  • Include header information, cookies, etc. to modify the answer.

  • Input checking. (Highly imp)

How to Implement a Filter?

If you want to implement the Filter API (or interface) effectively, make sure you remember the three crucial methods – init(), doFilter(), and destroy (). Overriding these methods is necessary for proper lifecycle management of a filter. Also note that while executing the FilterChain using the doFilter() method with ServletRequest, ServletResponse.

Example of Filter

In this illustration, we are only providing data about the filter that is automatically called after the request’s post-processing.

Index.html

Example

<a href="servlet1">click here </a>

Myfilter.java

Example

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();  
      out.print("filter is invoked before");  
          
      chain.doFilter(req, resp);//sends request to next resource  
          
      out.print("filter is invoked after");  
   }  
   public void destroy() {}  
}

HelloServlet.java

Example

import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
  
public class HelloServlet 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<br>");             
   }   
}

Web.xml

Example

<web-app>   
   <servlet>  
      <servlet-name>s1</servlet-name>  
      <servlet-class>HelloServlet</servlet-class>  
   </servlet>  
  
   <servlet-mapping>  
      <servlet-name>s1</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>

Conclusion

Taking steps towards securing your web application's functionality and enhancing its competitive edge could involve using filters during Java Servlet development. These powerful tools offer developers an array of advantages such as customization implementation for cross-cutting concerns like logging or performance monitoring while simultaneously improving reliability and efficiency. It's worth noting however that optimization should be considered so as not to negate these benefits with excessive overhead.

Updated on: 01-Aug-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements