- 过滤器和监听器是基于serlvet。
- 拦截器是基于Spring MVC框架。
过滤器:
针对web应用的请求及响应进行过滤处理。
主要应用:用户权限验证,跨域的处理,编码的处理 等等
springboot实现过滤器的方式有两种:
- 声明式,注解@webFilter
- 配置类注册过滤器
实现Filter过滤器接口,主要有3个方法
- init:项目启动初始化过滤器
- desctory:项目关闭销毁过滤器(重点)
- doFilter请求访问执行过滤器
重写 doFilter()方法,实现自己的业务逻辑,filterChain.doFilter(httpServletRequest, httpServletResponse);方法前写请求逻辑,
方法后写响应逻辑,filterChain.doFilter(httpServletRequest, httpServletResponse)是将请求和响应结果交给下一个过滤器,因为可能会配置多个过滤器。如下图:
代码如下:
实现过滤器
package com.zxy.loglearn.config.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* zhouxy.add 20191225
*/
@Slf4j
//@WebFilter(urlPatterns = "/*",filterName = "logFilter")
public class FilterConfigure implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
/**
* 项目启动是初始化过滤器,只执行一次
* filterConfig:过滤器相关参数
*/
log.info("open on the filter <|-.-|> <|-.-|> <|-.-|> <|-.-|>");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
/**
* 请求/响应在进入serlvet之前进行预处理
* servletRequest:请求对象
* servletResponse:响应对象
* filterChain:过滤链,放行此次过滤内容
*/
log.info("this is filter , go here");
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
//filterChain.doFilter前写请求业务逻辑
filterChain.doFilter(httpServletRequest, httpServletResponse);
//filterChain.doFilter后写响应业务逻辑
}
@Override
public void destroy() {
/**
* 关闭服务时,执行此方法销毁过滤器
*/
log.info("close on the filter <|-.-|> <|-.-|> <|-.-|> <|-.-|>");
}
}
向是spring注册过滤器
package com.zxy.loglearn.config;
import com.zxy.loglearn.config.filter.FilterConfigure;
import com.zxy.loglearn.config.listener.ListenerConfig;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @USER: zhouxy
* @DATE: 2019/12/26 14:57
**/
@Configuration
public class ServletConfigure {
/**
* 注册监听bean
* @return
*/
@Bean
public ServletListenerRegistrationBean registerListener() {
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
bean.setListener(new ListenerConfig());
return bean;
}
/**
* 向spring注册过滤器
* @return
*/
@Bean
public FilterRegistrationBean<FilterConfigure> filterRegistrationBean1() {
FilterRegistrationBean<FilterConfigure> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new FilterConfigure());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setOrder(1);//多个filter的时候order的数值越小 则优先级越高
return filterRegistrationBean;
}
}