Operation example of adding filter method in springboot

Time:2021-6-9

This paper describes the operation of adding filter method in springboot with an example. The details are as follows:

When accessing the server, we need to control whether the user allows permission or not. At this time, we can use the filter.

The method to configure the filter in springboot is as follows:

Write filter code:


package com.neo.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
  @Override
  public void destroy() {
  }
  @Override
  public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) srequest;
    System.out.println("this is MyFilter,url :"+request.getRequestURI());
    filterChain.doFilter(srequest, sresponse);
  }
  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

Write load filter code:


package com.neo.conf;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.neo.filter.MyFilter;
import com.neo.filter.MyFilter2;
@Configuration
public class WebConfiguration {
  @Bean
  public FilterRegistrationBean registerFilter() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("MyFilter");
    registration.setOrder(1);
    return registration;
  }
  @Bean
  public FilterRegistrationBean registerFilter2() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter2());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("MyFilter2");
    registration.setOrder(2);
    return registration;
  }
}

Here we see that we have registered two filters, and the execution order of the filters is determined by setorder.

More about Java related content, interested readers can see our special topics: “spring framework introduction and advanced tutorial”, “Java data structure and algorithm tutorial”, “Java operation DOM node skills summary”, “java file and directory operation skills summary” and “Java cache operation skills summary”

I hope this article will be helpful to you in Java programming.