java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot使用过滤器

springboot使用过滤器详解

作者:天空中那座城

本文主要介绍了过滤器的基本概念,过滤器的生命周期,以及如何通过注解方式和非注解方式实现过滤器,过滤器是客户端与服务器资源文件之间的一道过滤网,能够帮助我们过滤不符合要求的请求,通常用作Session校验

一:过滤器

1.过滤器介绍

过滤器是处于客户端与服务器资源文件之间的一道过滤网,帮助我们过滤一些不符合要求的请求。

通常用作 Session校验,判断用户权限。

2.过滤器生命周期

使用过滤器很简单,只需要实现Filter类,然后重写它的3个方法即可。

二:使用注解方式实现过滤器(@WebFilter)

1.在springboot 启动类添加该注解@ServletComponentScan

@SpringBootApplication
@ServletComponentScan // 过滤器
public class Springboot02WebTestApplication {
    SpringApplication.run(Springboot02WebTestApplication.class, args);
}

2.写个过滤器类,实现Filter接口

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

// urlPatterns 过滤路径  filterName 过滤器name
@WebFilter(urlPatterns = "/user/*", filterName = "tokenFilter1")
public class TokenFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        System.out.println(token);
        //该方法执行后直接运行至下一个过滤器
        if(token!=null){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = servletResponse.getWriter();
            JSONObject res = new JSONObject();
            res.put("msg", "错误");
            res.put("success", "false");
            out.append(res.toString());
        }
    }

    @Override
    public void destroy() {
//        Filter.super.destroy();
        System.out.println("destroy");
    }
}

3.访问,我使用的Postman软件进行的测试

添加请求头token信息,才可以访问成功。

三:使用非注解方式实现过滤器(直接注入到spring中)

1.Filter代码

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

public class TokenFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        System.out.println(token);
        //该方法执行后直接运行至下一个过滤器
        if(token!=null){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = servletResponse.getWriter();
            JSONObject res = new JSONObject();
            res.put("msg", "错误");
            res.put("success", "false");
            out.append(res.toString());
        }
    }

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

2.Filter配置文件

import com.itsufu.filter.TokenFilter2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FilterConfig {

    // Filter代码类
    @Bean
    public TokenFilter2 tokenFilter2() {
        return new TokenFilter2();
    }

    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(TokenFilter2 tokenFilter2) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(tokenFilter2);
        filterRegistrationBean.setOrder(2);
        filterRegistrationBean.addUrlPatterns("/user/*");
        filterRegistrationBean.setName("tokenFilter2");
        return filterRegistrationBean;
    }
}

测试与注解式一样。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文