SpringBoot graphic tutorial 6 - use of filters in SpringBoot

If there is the concept of flying in the sky, there must be the realization of landing

  • Ten times of concept is not as good as one time of code. My friend, I hope you can type all the code cases in this article

  • Praise before you see, and form a habit

Technical outline of SpringBoot graphic series tutorials

Teacher Lu's Java notes

SpringBoot graphic tutorial series article directory

  1. SpringBoot graphic tutorial 1 "concept + case thinking map" and "foundation"

  2. SpringBoot graphic tutorial 2 - use of logs "logback" and "log4j"

  3. SpringBoot graphic tutorial 3 - "first love complex" integration Jsp

  4. SpringBoot graphic Tutorial 4 - file upload and download of SpringBoot

  5. SpringBoot graphic tutorial 5 - using Aop in SpringBoot

preface

Filter is a very basic concept of Java Web, which belongs to Servlet. This article will use SpringBoot to configure filters. Before the code implementation, explain what a filter is through a simple small case.

Concept of filter: the technology provided in Servlet can filter the requests sent by the browser and decide whether to release or interrupt the requests.

  • The browser's request to the server will pass through the filter before reaching the server

  • The browser will respond to the browser first and then to the server

  • Based on the filter mechanism, we can process the request and response in the filter, and decide whether to release in the filter, such as verifying whether there is a sensitive string in the request, verifying whether there is a Session, etc.

Take chestnuts for example:

  • The filter is like the road card at the entrance of the village during the epidemic. You need to pass the road card whether you enter or leave the village

  • The staff of the road card (filter) will do some "operations" on you when you pass by, take your temperature, ask, and then deal with you, release or let you return the same way.

Use of filters in SpringBoot

All the contents of this article will be operated on the following demo. Please go to Git warehouse to download: https://gitee.com/bingqilinpeishenme/Lu-JavaNodes

1. Create filter class

/**
 * @WebFilter Servlet3 0. The newly added annotation, which originally implemented the filter, needs to be on the web XML, and now through this annotation, it will automatically scan and register when starting.
 *
 * @WebFilter filterName Defines the name of the registered filter
 * urlPatterns Define all requests to be intercepted
 *
 */
@WebFilter(filterName="userFilter",urlPatterns={"/*"})
public class UserFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(UserFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Filter initialization");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("Request processing");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//Simple session verification
        if (request.getSession().getAttribute("user")!=null) {
            //Request release
            filterChain.doFilter(request, response);
        }else {

        }

    }

    @Override
    public void destroy() {
        logger.info("Destroy");
    }
}

2.SpringBoot with filter scanning

@When WebFilter, servlet 3 0. The newly added annotation, which originally implemented the filter, needs to be on the web XML, and now through this annotation, it will automatically scan and register when starting.

To configure filter scanning in SpringBoot, you only need to add @ ServletComponentScan annotation to the startup class.

3. Set the execution sequence of multiple filters

You must have heard such a word: filter link. What is filter link? There are multiple filters, just like there are multiple road cards. When you have multiple filters, you need to specify the order of each filter. So how to specify the execution order of the filter?

Spring MVC through web XML can be set

In spring boot, you can register filters through FilterRegistrationBean.

  1. Create two Filter classes and delete the @ WebFilter annotation

     

  2. Configure FilterRegistrationBean through @ Bean in the startup class

@SpringBootApplication
@ServletComponentScan
public class AppRun {
    public static void main(String[] args) {
        //Parameter: start class object} main function parameter name
        SpringApplication.run(AppRun.class,args);
    }

    @Bean
    public FilterRegistrationBean  filterRegistrationBean(UserFilter userFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setFilter(userFilter);
        //Filter name
        registration.setName("userFilter");
        //Intercept path
        registration.addUrlPatterns("/*");
        //Set order
        registration.setOrder(10);
        return registration;
    }


    @Bean
    public FilterRegistrationBean  filterRegistrationBean2(User2Filter user2Filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
//Set filter
        registration.setFilter(user2Filter);
        //Filter name
        registration.setName("user2Filter");
        //Intercept path
        registration.addUrlPatterns("/*");
        //Set order
        registration.setOrder(20);
        return registration;
    }

    @Bean
    public UserFilter userFilter(){
        return new UserFilter();
    }

    @Bean
    public User2Filter user2Filter(){
        return new User2Filter();
    }
}

When registering multiple, you can register multiple filterregistrationbeans. The effects after startup are as follows:

summary

The above is the simple use of filters in SpringBoot. This article is the basic article, so the application of filters will be written in subsequent articles.

Congratulations on completing this chapter and applaud for you! If this article is helpful to you, please help to like, comment and forward, which is very important to the author. Thank you.

Let's review the learning objectives of this article again

  • Master the use of filters in SpringBoot

To learn more about SpringBoot usage, stay tuned for this series of tutorials.

Below, I am considerate. I have also prepared some self-test interview questions and project cases for my friend Meng. I hope you can forge iron into a hot iron and consolidate your knowledge.

Answers to last self-test interview questions

Meeting questions collection https://gitee.com/bingqilinpeishenme/Lu-JavaNodes

Self test interview questions (see next issue for answers)

nothing

Answers to small cases of self-test implementation projects in the previous period

See code cloud warehouse https://gitee.com/bingqilinpeishenme/Lu-JavaNodes

Small case of self-test implementation project (see next issue for answers)

This demand:

demo in exercise text

Keywords: Java

Added by NZ_Kiwis on Fri, 04 Mar 2022 00:53:56 +0200