过滤器
1.工作原理
2.创建Filter
2.1通过注解的方式实现
//创建一个类,实现Filter接口
@WebFilter(urlPatterns = "/myfilter") //urlPatterns表示需要拦截的路径
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("---------您已进入过滤器----------");
filterChain.doFilter(servletRequest,servletResponse);
}
}
//启动类上定义一个过滤器扫描器
@SpringBootApplication
@ServletComponentScan(basePackages = "com.liuhaiyang.springboot.filter") //filter类的地址
public class SpringbootTest14Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootTest14Application.class, args);
}
2.2 springboot的配置类实现
//写一个过滤器,不使用注解
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("---------您已进入过滤器222----------");
filterChain.doFilter(servletRequest,servletResponse);
}
}
//定义一个配置类,用于设定filter
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(new MyFilter());//构造函数中传入的是自定义的filter对象
//添加过滤路径
filterRegistrationBean.addUrlPatterns("/user/*");//拦截路径
return filterRegistrationBean;
}
如果想要实现重定向可以这么做
@Slf4j
@WebFilter(filterName = "first" , urlPatterns = "/*")
@Order(1)
public class Filter implements javax.servlet.Filter{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("---------您已进入过滤器---------");
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
String url = request.getRequestURI();
if(url.contains("login"))
{
filterChain.doFilter(servletRequest,servletResponse);
log.info("放行!!!");
}
else
{
//过滤器触发,进行重定向跳转,跳转到对应的控制器
String destination = "/user/error"; // 跳转目标
RequestDispatcher dispatcher = request.getRequestDispatcher(destination);
dispatcher.forward(request, response);
}
}
}```