Home > Java > javaTutorial > body text

How to integrate Filter in SpringBoot2

WBOY
Release: 2023-05-16 14:46:06
forward
1081 people have browsed it

First define a Filter for unified access URL interception. The code is as follows:

public class UrlFilter implements Filter {
  private Logger log = LoggerFactory.getLogger(UrlFilter.class);
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
  HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String requestURI = httpServletRequest.getRequestURI();
    StringBuffer requestURL = httpServletRequest.getRequestURL();
    log.info("requestURI:" +requestURI+" "+"requestURL:"+requestURL);
    chain.doFilter(httpServletRequest, response);
  }
}
Copy after login

Configure the SpringBoot filter chain class FilterRegistrationBean through javaConfig. The specific code is as follows:

@Configuration
public class FilterConfig {
  @Bean
  public FilterRegistrationBean filterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new UrlFilter());
    List<string> urlList = new ArrayList<string>();
    urlList.add("/*");
    registration.setUrlPatterns(urlList);
    registration.setName("UrlFilter");
    registration.setOrder(1);
    return registration;
  }
}</string></string>
Copy after login

FilterRegistrationBean method introduction:

  • registration.setFilter(Filter filter): Set our custom Filter object.

  • registration.setUrlPatterns(Collection urlPatterns): Set the collection of URLs that the custom Filter needs to intercept.

  • registration.setName(String name): Set the custom Filter name.

  • registration.setOrder(int order): Set the custom Filter interception order.

Test

Start the SpirngBoot project and access the index.html under our project through the browser.

How to integrate Filter in SpringBoot2

How to integrate Filter in SpringBoot2

The above is the detailed content of How to integrate Filter in SpringBoot2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template