springboot-添加过滤器
过滤器一次,顾名思义,过滤一些东西等等。那么怎么实现呢,具体代码如下
首先肯定需要建一个filter的包,创建一个过滤类实现filter接口,用来过滤
package com.gateway.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class UserFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest) servletRequest; HttpServletResponse response=(HttpServletResponse) servletResponse; System.out.println("过滤器实现"); chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } }
然后在启动类中将该过滤类加载进去
@Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(); List<String>urlPatterns=new ArrayList<String>(); filterRegistrationBean.setFilter(new UserFilter()); urlPatterns.add("/user/touser"); filterRegistrationBean.setUrlPatterns(urlPatterns); return filterRegistrationBean; }
由上可知,我们过滤的路径是/user/touser,那么过滤器和拦截器先进谁呢,debug测试即可得知,当路径/user/touser过来,先进入过滤器完成之后在进入拦截器,最后执行 完成之后进入controller