如何在 Spring Boot 应用程序中注册 JavaEE 过滤器?
Posted
技术标签:
【中文标题】如何在 Spring Boot 应用程序中注册 JavaEE 过滤器?【英文标题】:How to register a JavaEE filter in your Spring Boot application? 【发布时间】:2017-07-12 23:47:25 【问题描述】:我在基于Spring Boot
的REST
应用程序中有以下Spring Boot
控制器和JavaEE
过滤器类。请注意,我没有在此处配置web.xml
。
http://localhost:8080/api/products -> Returns 200
问题是拦截器/过滤器永远不会被调用。
ProductController.java
@RestController
@RequestMapping("/api")
public class ProductController
@Inject
private ProductService productService;
//URI: http://localhost:8080/api/products
@RequestMapping(value = "/products", method = RequestMethod.GET)
public ResponseEntity<Iterable<Product>> getAllProducts()
Iterable<Product> products = productService.getAllProducts();
return new ResponseEntity<>(products, HttpStatus.OK);
//URI: http://localhost:8080/api/products/50
@RequestMapping(value = "/products/productId", method = RequestMethod.GET)
public ResponseEntity<?> getProduct(@PathVariable Long productId)
Product product = productService.getProduct(productId);
return new ResponseEntity<>(product, HttpStatus.OK);
SecurityFilter.java
@WebFilter(urlPatterns = "/api/products/*")
public class SecurityFilter implements Filter
@Override
public void init(FilterConfig filterConfig) throws ServletException
//in the init method
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
//THIS METHOD NEVER GETS CALLED AND HENCE THIS NEVER GETS PRINTED ON CONSOLE.
//WHY ?????
System.out.println("**********Into the doFilter() method...........");
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
//move ahead
chain.doFilter(httpRequest, httpResponse);
@Override
public void destroy()
//nothing to implement
BasicRestApplication.java
@SpringBootApplication
public class BasicRestApplication
public static void main(String[] args)
SpringApplication.run(BasicRestApplication.class, args);
我已经浏览了此链接How to add a filter class in Spring Boot?,但它并没有明确说明需要添加什么以在Spring Boot
注册过滤器的位置。
【问题讨论】:
【参考方案1】:从这里找到解决方案Add a Servlet Filter in a Spring Boot application
创建了一个新的配置类并注册了过滤器类。
@Configuration
public class ApplicationConfig
@Bean
public Filter securityFilter()
return new SecurityFilter();
【讨论】:
以上是关于如何在 Spring Boot 应用程序中注册 JavaEE 过滤器?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Spring Boot 注册辅助 servlet?
如何从使用 Spring Cloud Eureka 服务器注册的 Spring Boot 应用程序中公开 Prometheus 指标
如何从 Spring Boot 应用程序中的所有子包中注册 bean?