Spring拦截服务【一】(SpringBoot使用第三方过滤器Filter直接加入项目)

正常来说,我们自定义拦截器Filter是需要@Component注解让我们的拦截器注入Bean,从而让拦截器生效。当需要第三方Filter的时候,我们可以不需要使用@Component注解,从而使用它。

一般使用Filter,(ps:下面这样使用的话他是对所有的路径都进行过滤的。)

package com.yhn.web.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
import java.util.Date;

/**
 * 自定义过滤器
 * Created by yhn on 2017/12/3
 */
//@Component
//如果注解Component不在则当作第三方拦截器使用 在    com.yhn.web.config.WebConfig
public class TimeFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("time filter init");
    }




@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    System.out.println("time filter start");
    long start =new Date().getTime();
    filterChain.doFilter(request,response);
    System.out.println("用时:"+(new Date().getTime()-start));
    System.out.println("time filter finish");
}

@Override
public void destroy() {
    System.out.println("time filter destroy");
}

}

而对使用第三方Filter通过配置Bean导入项目(与写xml效果相同)
SpringBoot的出现就是为了简化配置文件xml。

package com.yhn.web.config;
import com.yhn.web.filter.TimeFilter;
import com.yhn.web.interceptor.TimeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by yhn on 2017/12/3.
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
    @Autowired
    private TimeInterceptor timeInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }

@Bean
public FilterRegistrationBean timeFile(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    TimeFilter timeFilter = new TimeFilter();
    registrationBean.setFilter(timeFilter);
    List<String> url = new ArrayList<>();
    url.add("/*");  //对所有路径起作用。对项目来说看其所需
    registrationBean.setUrlPatterns(url);
    return registrationBean;
   }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值