欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot学习笔记12-SpringBoot 中使用 Filter

程序员文章站 2022-07-13 13:37:25
...

通过2种方式实现
方式一,通过注解方式实现;
1、编写一个Servlet3的注解过滤器;
创建一个filter包。

package com.springboot.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns="/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("您已进入filter过滤器,您的请求正常,请继续遵规则...");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}

2、在main方法的主类上添加注解:

@ServletComponentScan(basePackages={"com.springboot.web.servlet","com.springboot.web.filter"})

运行截图如下:
SpringBoot学习笔记12-SpringBoot 中使用 Filter

方式二,通过Spring boot的配置类实现;
1、编写一个普通的Filter

package com.springboot.web.filter;

import javax.servlet.*;
import java.io.IOException;

public class HeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("hi您已进入filter过滤器,您的请求正常,请继续遵规则...");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}

2、编写一个Springboot的配置类;
编写个ServletConfig配置类,注意一定要加@Configuration

package com.springboot.web.config;

import com.springboot.web.filter.HeFilter;
import com.springboot.web.servlet.HeServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/** springboot没有xml , @Configuration可以表示一个spring的配置文件,比如:applicationContext.xml */
@Configuration //一定要加上这个注解,成为Springboot的配置类,不然不会生效
public class ServletConfig {

    @Bean //这个注解就将这个ServletRegistrationBean变成一个Spring的bean类。
    public ServletRegistrationBean heServletRegistrationBean(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(), "/heServlet");
        return registration;
    }

    @Bean
    public ServletRegistrationBean sheServletRegistrationBean(){
        ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(), "/sheServlet");
        return registration;
    }
    @Bean
    public FilterRegistrationBean heFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new HeFilter());
        registration.addUrlPatterns("/*");
        return registration;
    }

}

运行截图如下:
SpringBoot学习笔记12-SpringBoot 中使用 Filter