赞
踩
原文网址:SpringBoot--过滤器(Filter)--使用/教程/实例_IT利刃出鞘的博客-CSDN博客
说明
本文用示例介绍SpringBoot(SpringMVC)中的过滤器的用法。
Filter可以有多个。一个filter执行完之后会执行另外一个。
过滤器的使用场景
两种方式注册filter(两种方式的本质都是一样的,都是去FilterRegistrationBean注册自定义Filter ):
1、使用Spring Boot提供的FilterRegistrationBean注册Filter
2、使用原生servlet注解定义Filter。缺点:无法指定过滤器顺序
定义Filter
- package com.example.filter;
-
- import javax.servlet.*;
- import javax.servlet.http.HttpServletRequest;
- import java.io.IOException;
-
- public class MyFilter implements Filter {
- @Override
- public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
- System.out.println("MyFilter.init");
- System.out.println(" 过滤器名:" + filterConfig.getFilterName());
- }
-
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
- // do something 处理request 或response
- System.out.println("MyFilter.doFilter");
-
- if (servletRequest instanceof HttpServletRequest) {
- System.out.println(" URL:" + ((HttpServletRequest)servletRequest).getRequestURL());
- }
-
- // 调用filter链中的下一个filter
- filterChain.doFilter(servletRequest,servletResponse);
- }
-
- @Override
- public void destroy() {
- System.out.println("MyFilter.destroy");
- }
- }
注册自定义Filter
- package com.example.filter;
-
- import org.springframework.boot.web.servlet.FilterRegistrationBean;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class FilterConfig {
-
- @Bean
- public FilterRegistrationBean registrationBean() {
- FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
- filterRegistrationBean.addUrlPatterns("/*");
- return filterRegistrationBean;
- }
- }
上边是部分内容,为便于维护,全文已迁移到此网址:SpringBoot-过滤器(Filter)-使用/教程/实例 - 自学精灵
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。