使用过滤器只需配置两个东西:
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注入等危险。
如上例当输入参数username有值时,即过滤掉,并返回提示信息。
效果如下