方法1
1、新建一个类实现Filter接口,重写相关方法,并加上@WebFilter注解;urlPatterns为请求路径
@WebFilter(urlPatterns = "/first")
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("----------------过滤器执行之前----------------");
String username = servletRequest.getParameter("username");
if(null == username || username.isEmpty()){
PrintWriter writer = servletResponse.getWriter();
writer.write("username is null");
writer.flush();
writer.close();
return;
}
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("----------------过滤器执行之后----------------");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----------------init----------------");
}
@Override
public void destroy() {
System.out.println("----------------destory----------------");
}
}
2、启动类上加上@ServletComponentScanz注解
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ServletComponentScan
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BootDemoApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);
ApplicationContext ac = springApplication.run(args);
}
}
方法2
1、新建一个类实现Filter接口,重写相关方法
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("----------------过滤器执行之前----------------");
String username = servletRequest.getParameter("username");
if(null == username || username.isEmpty()){
PrintWriter writer = servletResponse.getWriter();
writer.write("username is null");
writer.flush();
writer.close();
return;
}
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("----------------过滤器执行之后----------------");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----------------init----------------");
}
@Override
public void destroy() {
System.out.println("----------------destory----------------");
}
}
2、在SpringBoot启动类上加上@ServletComponentScan注解扫描Filter,并将Filter注册到容器
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ServletComponentScan
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BootDemoApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);
ApplicationContext ac = springApplication.run(args);
}
@Bean
public FilterRegistrationBean flterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new FirstFilter());
filterRegistrationBean.addUrlPatterns("/first");
return filterRegistrationBean;
}
}