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- package com.ekiras.filter;
- import org.springframework.core.Ordered;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- import javax.servlet.*;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- /**
- * @author ekansh
- */
- @Component
- @Order(Ordered.HIGHEST_PRECEDENCE)
- public class SecurityFilter implements Filter {
- private static final boolean CONDITION = true;
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- if(CONDITION==true)
- chain.doFilter(request,response);
- else{
- ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_BAD_REQUEST);
- }
- }
- @Override
- public void destroy() {
- }
- }
This is how you can create the filter and register it in the Spring Boot Application.
No comments: