两种方法
方法一:
正常创建好Filter类,配置完成
package clc.user.filter; 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.annotation.WebFilter; import java.io.IOException; /** * ClassName: FirstFilter<br/> * Description: <br/> * date: 2019/4/1 5:31 PM<br/> * * @author chengluchao * @since JDK 1.8 */ @WebFilter(filterName = "FirstFilter", urlPatterns = {"/FirstFilter", "/FirstServlet"}) public class FirstFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init-FirstFilter"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("doFilter-FirstFilter"); } @Override public void destroy() { System.out.println("destroy-FirstFilter"); } }
启动类使用注解ServletComponentScan
@SpringBootApplication @ServletComponentScan public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } }
方法二:
写好Filte但不进行配置,在启动类中进行配置
package clc.user.filter; 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.annotation.WebFilter; import java.io.IOException; /** * ClassName: SecondFilter<br/> * Description: <br/> * date: 2019/4/1 5:31 PM<br/> * * @author chengluchao * @since JDK 1.8 */ public class SecondFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init-SecondFilter"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("doFilter-SecondFilter"); } @Override public void destroy() { System.out.println("destroy-SecondFilter"); } }
@SpringBootApplication public class UserServiceApplication2 { @Bean public ServletRegistrationBean getServletRegistrationBean() { ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet()); bean.addUrlMappings("/SecondServlet"); return bean; } @Bean public FilterRegistrationBean getFilterRegistrationBean() { FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter()); bean.addUrlPatterns("/SecondServlet","/123"); return bean; } public static void main(String[] args) { SpringApplication.run(UserServiceApplication2.class, args); } }
注意,所有的路径必须以"/"开头