Filter过滤器

◼ 过滤器(Filter)可以动态地拦截请求和响应。
◼ 应用场景:过滤敏感词汇、防止SQL注入、设置字符编码、进行URL级
别的权限访问控制、压缩响应信息等。

  • 启动文件DemoApplication.java加上@ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class DemoApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(DemoApplication.class, args);
    }

}

后台代码:TestController.java

@RestController
public class TestController {
   

    @RequestMapping("/")
    public String test() {
   
        return "hello";
    }

}

过滤器:
◼ 新建 Filter 包,并新建 MyFilter 类
◼ 启动类上添加 @ServletComponentScan
文件位置:

  • MyFilter.java
package com.example.demo.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class MyFilter implements Filter {
   
    //黑名单 简单模拟一下
    private List<String> IPList = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    //过滤器初始化
        IPList.add("127.0.0.1"); // 本机地址
        IPList.add("0:0:0:0:0:0:0:1"); // IPv6 的本机地址
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {
   
//黑名单过滤
        String ip = servletRequest.getRemoteAddr(); // 获得客户端 ip 地址
        System.out.println(ip); //控制台上查看一下
        if (IPList.contains(ip)) {
   
            servletResponse.setContentType("text/html;charset=utf-8"); //设置响应的字符集(避免中文乱码)
            servletResponse.getWriter().println("你已被列入黑名单!");
        } else {
   
            filterChain.doFilter(servletRequest, servletResponse); //放行
        }
    }
}


运行结果: