方式一 :通过注解方式实现
项目名称:032-springboot-filter-01
1.通过注解方式创建一个Filer
在com.abc.springboot.filter包下创建MyFilter
package com.abc.springboot.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* ClassName:MyFilter
* Package:com.abc.springboot.filter
* Description:
*/
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("您已进入filter过滤器,您的请求正常,请继续遵循规则....");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2.在主应用程序Application类上添加@ServletComponentScan("basePackages = "com.abc.springboot.filter")
package com.abc.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan(basePackages = "com.abc.springboot.filter")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.启动应用SpringBoot,浏览器访问测试
因为过滤所有请求,所以随便输入一个地址,控制台都会输出
项目名称:033-springboot-filter-02
1.创建一个普通的Filter
在com.abc.springboot.filter包下,创建HeFilter类
package com.abc.springboot.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* ClassName:HeFilter
* Package:com.abc.springboot.filter
* Description:
*/
@WebFilter(urlPatterns = "/*")
public class HeFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("He已进入Filter过滤器,您的请求正常,请继续遵循规则...");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2.编写一个Spring Boot的配置类,在该类中注册Filter
在com.abc.springboot.config包下创建FilterConfig配置类
package com.abc.springboot.config;
import com.abc.springboot.filter.HeFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* ClassName:FilterConfig
* Package:com.abc.springboot.config
* Description:
*/
@Configuration //该注解将此类标记为配置类
public class FilterConfig {
@Bean
public FilterRegistrationBean heFilterRegistration() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new HeFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
3.启动应用SpringBoot,浏览器访问测试
因为过滤所有请求,所以随便输入一个地址,控制台都会输出