Spring Boot 使用 Filter 的正确姿势!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import javax.servlet.*;
import java.io.IOException;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public FilterRegistrationBean<DemoFilter> demoFilter() {
FilterRegistrationBean<DemoFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new DemoFilter());
registrationBean.addUrlPatterns("/demo/*");
registrationBean.setOrder(1);
return registrationBean;
}
public static class DemoFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化代码
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 在请求处理之前可以添加逻辑
chain.doFilter(request, response);
// 在请求处理之后可以添加逻辑
}
@Override
public void destroy() {
// 销毁代码
}
}
}
这段代码定义了一个名为DemoFilter
的简单过滤器,并通过FilterRegistrationBean
将其注册到Spring Boot应用的过滤器链中。过滤器会拦截以/demo/*
开头的URL路径。这是在Spring Boot中配置和使用Filter的标准方式。
评论已关闭