过滤器的应用-Filter

过滤器

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);
        }
    }
}```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值