💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # 简介 springboot内置一些Filter,比如编码的OrderedCharacterEncodingFilter和请求转化的HiddenHttpMethodFilter 2种实现,第一种使用@WebFilter,第二种使用FilterRegistrationBean. 第一种定义的优先级不生效,用第二种 自定义Filter步骤 * 实现Filter接口,实现其中的doFilter方法 * 添加@Configuration注解,将自定义Filter加入过滤链 ~~~ import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("this is MyFilter, url: " + request.getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } } ~~~ ~~~ import com.example.demo.filter.MyFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebConfiguration { @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter()); registration.addUrlPatterns("/*"); registration.setName("MyFilter"); registration.setOrder(6); return registration; } } ~~~