SpringBoot : How to create a Filter in Spring Boot Application

Points To Remember


  • Implement the class Filter.
  • Add @Configuration annotation to the class to register it as a filter bean.
  • Call method 
    • filterChain.doFilter(resquest,response) to continue the request flow
    • Call method sendError to send error,
      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST);
    • Call method sendRedirect to redirect request to error handler
      ((HttpServletResponse)response).sendRedirect("/errorUrl");

How to create a Filter in Spring Boot Application

IN order to make a filter, we have create a class SecurityFilter
  1. package com.ekiras.filter;  
  2.   
  3. import org.springframework.core.Ordered;  
  4. import org.springframework.core.annotation.Order;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. import javax.servlet.*;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import java.io.IOException;  
  10.   
  11. /** 
  12.  * @author ekansh 
  13.  */  
  14. @Component  
  15. @Order(Ordered.HIGHEST_PRECEDENCE)  
  16. public class SecurityFilter implements Filter {  
  17.   
  18.     private static final boolean CONDITION = true;  
  19.   
  20.     @Override  
  21.     public void init(FilterConfig filterConfig) throws ServletException {  
  22.   
  23.     }  
  24.   
  25.     @Override  
  26.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
  27.         if(CONDITION==true)  
  28.             chain.doFilter(request,response);  
  29.         else{  
  30.             ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_BAD_REQUEST);  
  31.         }  
  32.   
  33.     }  
  34.   
  35.     @Override  
  36.     public void destroy() {  
  37.   
  38.     }  
  39. }  

This is how you can create the filter and register it in the Spring Boot Application.

No comments:

Powered by Blogger.