欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(二)、SpringBoot 自定义 filter(过滤器)

程序员文章站 2022-05-23 08:37:40
...

可以前往第一篇博客查看目录结构 --> 这里

一、在demo模块 src\main\java\com\zeke下创建 config、controller、dto、filter目录

(二)、SpringBoot 自定义 filter(过滤器)

二、在dto包下创建一个User类

public class User {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

三、controller包下创建UserController类

@RestController
public class UserController {

    @GetMapping("/user")
    public List<User> query(@RequestParam(value = "username",defaultValue = "666") String username){
        System.out.println(username);
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
    }

}

四、在filter包下创建TimeFilter类,用于自定义filter

@Component
public class TimeFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter init");
    }

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

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

五、在config包下创建WebConfig类

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{

    /**
     * 配置自定义过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean timeFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        TimeFilter timeFilter = new TimeFilter();
        filterRegistrationBean.setFilter(timeFilter);

        //自定义需要的过滤url
        List<String> list = new ArrayList<>();
        list.add("/*");
        filterRegistrationBean.setUrlPatterns(list);
        return filterRegistrationBean;
    }

}

六、启动项目 输入 localhost/user ,打开IDEA控制台查看效果

(二)、SpringBoot 自定义 filter(过滤器)

(二)、SpringBoot 自定义 filter(过滤器)