SpringBoot中拦截器和过滤器的使用
一、拦截器
三种方式
- 继承WebMvcConfigurerAdapter spring5.0 以弃用,不推荐
- 实现WebMvcConfigurer 推荐
- 继承WebMvcConfigurationSupport 会导致springboot自动配置失效
所以推荐使用第二种,方案,接口中的方法是default ,不必实现所有方法
代码:
import com.starfast.admin.interceptor.PermissionInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author DUCHONG **/ @Configuration public class AdminWebConfig implements WebMvcConfigurer { @Autowired private PermissionInterceptor permissionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(permissionInterceptor) .addPathPatterns("/**") .excludePathPatterns("/monitor/druid/*") .excludePathPatterns("/user/login") .excludePathPatterns("/user/logout") ; } }
二、过滤器
跨域过滤器
import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CrossOriginFilter implements Filter { public void destroy() { System.out.println("----Filter销毁----"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse)response; httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.setHeader("Access-Control-Allow-Headers", "Authentication"); // 执行目标资源,放行 filterChain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { System.out.println("----Filter初始化----"); } }
添加到配置中,也可以和拦截器的配置放在一块
import com.starfast.admin.filter.CrossOriginFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Arrays; /** * 跨域过滤器 * @author DUCHONG **/ @Configuration public class ServletConfig { @Bean public FilterRegistrationBean crossOriginFilter(){ FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(); filterRegistrationBean.setFilter(new CrossOriginFilter()); filterRegistrationBean.setUrlPatterns(Arrays.asList("/router/**")); return filterRegistrationBean; } }