springboot--filter--视频笔记

方式1:

①实现接口javax.servlet.Filter,重写Filter的doFilter等方法,并用javax.servlet.annotation.WebFilter注解指定过滤路径


package com.example.demo.filter;
...

@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("自定义MyFilter");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

 ②启动类添加Filter扫描注解 org.springframework.boot.web.servlet.ServletComponentScan,扫描指定包

@SpringBootApplication
@ServletComponentScan(basePackages = {"com.example.demo.servlet", "com.example.demo.filter"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

方式2:

①实现接口javax.servlet.Filter,重写Filter的doFilter等方法

package com.example.demo.filter;
...

public class MyConfFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("自定义MyConfFilter");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

②编写Filter配置类,配置自定义的Filter

package com.example.demo.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
...

@Configuration //配置类
public class FilterConfig {

    @Bean //注册为FilterRegistrationBean
    public FilterRegistrationBean myConfFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyConfFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值