我的一个老项目从SpringMvc升级到了SpringBoot、项目中使用了两个过滤器,分别是XSS注入过滤器和CSRF攻击过滤器。

Servlet 三大组件 Servlet、Filter、Listener 在传统项目中需要在 web.xml 中进行相应的配置。

Servlet 3.0 开始在 javax.servlet.annotation 包下提供 3 个对应的 @WebServlet、@WebFilter、@WebListener 注解来简化操作,@WebServlet、@WebFilter、@WebListener 写在对应的 Servlet、Filter、Listener 类上作为标识,从而不需要在 web.xml 中进行配置了。

因此新的代码如下

@Component

@WebFilter(urlPatterns = {"/*"}, filterName = "csrfFilter")

public class WebCsrfFilter implements Filter{

}

@Component

@WebFilter(urlPatterns = {"/*"}, filterName = "xssFilter")

public class WebXssFilter extends XssFilter {

}

在测试过程中发现设置的Filter没有生效,经过排查发现需要注意的是:Spring Boot 应用中这三个注解默认是不被扫描的,需要在项目启动类上添加 @ServletComponentScan 注解, 表示对 Servlet 组件扫描。

因此在SpringBootApplication项目上需要使用@ServletComponentScan注解后,Servlet、Filter、Listener才可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication

@ServletComponentScan(basePackages = "com.web.global.filter")

public class WebApplication extends SpringBootServletInitializer{

public static void main(String[] args) {

SpringApplication.run(WebApplication.class, args);

}

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: