Spring Boot框架的过滤器(Filters)和拦截器(Interceptors)使用-过滤器(Filter)示例

过滤器主要用于对请求进行预处理和响应进行后处理,适用于处理所有请求。例如,我们可以创建一个简单的过滤器来记录请求的处理时间。

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

public class LogFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long endTime = System.currentTimeMillis();
        System.out.println("Request processed in " + (endTime - startTime) + " ms");
        System.out.println("Request URI: " + ((HttpServletRequest) request).getRequestURI());
    }

    @Override
    public void destroy() {
    }
}

接着,在Spring Boot的配置类中注册这个过滤器:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<LogFilter> loggingFilter(){
        FilterRegistrationBean<LogFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new LogFilter());
        registrationBean.addUrlPatterns("/api/*");

        return registrationBean;
    }
}
上一篇:二维数组中a[0] 和 &a[0]的区别


下一篇:如何本地部署Elasticsearch+cpolar实现公网查询与管理内网数据