在这个快速教程中,我们将探索如何在 Spring Boot 的帮助下定义自定义过滤器并指定它们的调用顺序。
顾名思义,过滤器用于对对资源的请求或来自资源的响应执行过滤,或两者兼而有之。 Spring Boot 提供了几个选项来在 Spring Boot 应用程序 中注册自定义过滤器。让我们看看不同的选项。
为了创建过滤器,我们需要简单地实现 Filter 接口:
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating Custom filter ##########");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
LOGGER.info("Logging Request - #### ---> {} : {}", request.getMethod(), request.getRequestURI());
//call next filter in the filter chain
filterChain.doFilter(request, response);
LOGGER.info("Logging Response - ##### --> :{}", response.getContentType());
}
@Override
public void destroy() {
LOGGER.info("########## Destroying Custom filter ##########");
}
}
让我们快速看一下上面代码中的一些重点
@Component
注解注册的过滤器。最高阶过滤器首先运行。当我们想要在预定义的订单上执行我们的自定义过滤器时,这很有用。
@Component
@Order(1)
public class CustomFirstFilter implements Filter {
}
@Component
@Order(2)
public class CustomSecondFilter implements Filter {
}
在上面的代码中,CustomFirstFilter 将在 CustomSecondFilter 之前运行。
数字越小,优先级越高
在上面的示例中,我们的过滤器默认为我们应用程序中的所有 URL 注册。但是,我们有时可能希望过滤器仅适用于某些 URL 模式。
在这种情况下,我们必须从过滤器类定义中删除 @Component 注释并使用 **FilterRegistrationBean 注册过滤器:
public class MyCustomFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(MyCustomFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating MyCustomFilter filter ##########");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
LOGGER.info("This Filter is only called when request is mapped for /filterExample resource");
//call next filter in the filter chain
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
LOGGER.info("########## Destroying MyCustomFilter filter ##########");
}
}
使用 FilterRegistrationBean 注册自定义过滤器。
@Configuration
public class ApplicationConfig {
@Bean
public FilterRegistrationBean<MyCustomFilter> filterRegistrationBean() {
FilterRegistrationBean < MyCustomFilter > registrationBean = new FilterRegistrationBean();
MyCustomFilter myCustomFilter = new MyCustomFilter();
registrationBean.setFilter(myCustomFilter);
registrationBean.addUrlPatterns("/filterExample/*");
registrationBean.setOrder(2); //set precedence
return registrationBean;
}
}
现在让我们创建一个简单的 Spring MVC 控制器并向其发送 HTTP 请求:
@Controller
public class FilterExampleController {
@GetMapping(value = "/filterExample")
public String customGreetings() {
return "Hello From Custom Filter Example";
}
}
我们可以通过以下方式运行我们的 Spring Boot 应用程序。
1。使用 Maven 命令:下载项目源代码。使用命令提示符转到项目的根文件夹并运行命令。
mvn spring-boot:run
Tomcat 服务器将启动。
2。使用 Eclipse:使用文末给出的下载链接下载项目源代码。将项目导入eclipse。使用命令提示符,转到项目的根文件夹并运行。
mvn clean eclipse:eclipse
然后在eclipse中刷新项目。单击 Run as -> Java Application 运行主类 SpringBootMainClassApplication
。 Tomcat 服务器将启动。
3。使用 Executable JAR:使用命令提示符,转到项目的根文件夹并运行命令。
mvn clean package
我们将在目标文件夹中获得可执行的 JAR Spring-Boot-Main-Class-0.0.1-SNAPSHOT.jar。将此 JAR 运行为
java -jar target/Spring-Boot-Main-Class-0.0.1-SNAPSHOT.jar
Tomcat 服务器将启动。
现在我们准备好测试应用程序了。运行以下 URL。
http://localhost:8081
2019-10-07 19:58:10.329 INFO 1896 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-10-07 19:58:10.333 INFO 1896 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-10-07 19:58:10.368 INFO 1896 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 35 ms
2019-10-07 19:58:10.388 INFO 1896 --- [nio-8081-exec-1] c.d.e.S.filter.CustomFilter : Logging Request - #### ---> GET : /home
2019-10-07 19:58:10.481 INFO 1896 --- [nio-8081-exec-1] c.d.e.S.filter.CustomFilter : Logging Response - ##### --> :null
2019-10-07 19:58:21.092 INFO 1896 --- [nio-8081-exec-3] c.d.e.S.filter.CustomFilter : Logging Request - #### ---> GET : /filterExample
2019-10-07 19:58:21.092 INFO 1896 --- [nio-8081-exec-3] c.d.e.S.filter.MyCustomFilter : This Filter is only called when request is mapped for /filterExample resource
2019-10-07 19:58:21.116 INFO 1896 --- [nio-8081-exec-3] c.d.e.S.filter.CustomFilter : Logging Response - ##### --> :null
在本文中,我们总结了如何在 Spring Boot webapp 中定义自定义过滤器。与往常一样,可以找到代码片段 over on GitHub。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.dailycodebuffer.com/how-to-add-a-filter-in-spring-boot/
内容来源于网络,如有侵权,请联系作者删除!