SpringBoot自定义过滤器Filter

发布时间:2024年01月09日


前言

SpringBoot 自定义一个过滤器

示例

1. 自定义过滤器

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
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 {
        log.info("MyFilter 执行 doFilter, request addr={}, host={}", servletRequest.getRemoteAddr(), servletRequest.getRemoteHost());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

2. 配置类

import com.idiudiu.api.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebServletConfig {
    @Bean
    public FilterRegistrationBean<MyFilter> myFilter() {
        FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setName("myFilter");
        registrationBean.setFilter(new MyFilter()); // 注意:MyFilter 不能加 @Component, @Service... 注解
        registrationBean.addUrlPatterns("/*"); // 所有路径
        registrationBean.setOrder(1); // 优先级, 值越小 Filter 越靠前
        return registrationBean;
    }
}
文章来源:https://blog.csdn.net/qq_40213825/article/details/135365304
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。