java

关注公众号 jb51net

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

springboot实现过滤器的示例代码

作者:麦芽糖0219

JavaWeb开发中,过滤器Filter是三大组件之一,主要用于请求拦截和响应处理,如权限校验、日志记录、请求过滤等,本文就来介绍一下springboot实现过滤器的示例代码,感兴趣的可以了解一下

一 过滤器介绍

1.1 过滤器概念

过滤器,即filter,它是javaWeb三大组件之一(Servlet程序、Listener监听器、Filter过滤器)

作用:既可以对请求进行拦截,也可以对响应进行处理。常用于做权限检查,记录日志操作、拦截过滤请求、对请求字符设置编码等。

1.2 过滤器生命周期

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

二 SpringBoot中过滤器的两种实现方式

2.1 注解方式实现过滤器

首先需要在启动类加 @ServletComponentScan 注解,启动类如下

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@MapperScan("com.ts.myt.dao")
@ServletComponentScan // 过滤器
public class MytApplication {
    public static void main(String[] args) {
        SpringApplication.run(MytApplication.class, args);
    }
}

编写过滤器,实现Filter接口

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:sgw
 * @Date:2023/9/15
 * @Description: 使用注解方式实现过滤器(@WebFilter)
 */
@WebFilter(urlPatterns = "/user/*", filterName = "filter1")
public class MyFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
        logger.info("MyFilterInit1");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        logger.info("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        logger.info("token值:{}", 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();
        logger.info("destroy");
    }
}

上边对请求头header做了过滤,即请求头里必须含有key为token的值,才能继续访问具体接口,否则该请求就终止访问接口了

2.2 非注解方式实现过滤器(直接注入到spring中)

定义过滤器,同样实现Filter接口

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:sgw
 * @Date:2023/9/15
 * @Description: 过滤器实现方式二:使用非注解方式实现过滤器(直接注入到spring中)
 */
public class MyFilter2 implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MyFilter2.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("MyFilterInit2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        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");
    }
}

编写过滤器配置类

import com.ts.myt.filter.MyFilter2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @Author:sgw
 * @Date:2023/9/15
 * @Description: 方式二的过滤器配置文件
 */
@Configuration
public class MyFilter2Config {
    // Filter代码类
    @Bean
    public MyFilter2 myFilter2() {
        return new MyFilter2();
    }

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

效果与方式一一样。

到此这篇关于springboot实现过滤器的示例代码的文章就介绍到这了,更多相关springboot 过滤器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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