springboot中使用过滤器

转载:https://blog.csdn.net/weixin_45583482/article/details/125876364

使用过滤器只需配置两个东西:
1 在启动类上添加注解@ServletComponentScan

@SpringBootApplication
@ServletComponentScan
public class KafkaBeanTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public static void main(String[] args) {
        SpringApplication.run(KafkaBeanTest.class, args);
    }
}

2 编写WebFilter类,重写Filter接口

@WebFilter(filterName = "asshole", urlPatterns = "/*") /*urlPatterns指定匹配到的URL地址会在调用
Controller前先进入该doFilter方法,我这匹配所有*/
public class FilterDemo implements Filter {
    public void init(FilterConfig filterConfig) {
        System.out.println("过滤器启动");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("监听到了");
        String warn = servletRequest.getParameter("username");
        if (StringUtils.isEmpty(warn)) {
            filterChain.doFilter(servletRequest, servletResponse);//通过了filter,进入Controller层
            return;
        }
        PrintWriter writer = servletResponse.getWriter();
        writer.write("don't put any security name on web\n");
        writer.flush();
        writer.close();
    }

    public void destroy() {
        System.out.println("过滤器关闭");
    }
}

当匹配到URL后,便会在调用Controller前先进入FilterDemo类的doFilter方法。在此方法内编写逻辑以此达到过滤非安全信息,以及避免SQL注入等危险。

posted @ 2022-11-27 20:06  远洪  阅读(631)  评论(0)    收藏  举报