整体认识:过滤器和拦截器是我们常说的AOP思想的两个具体实现,接下来我们一起看看它们之间的区别和具体的使用。
1.过滤器和拦截器的区别
使用范围:过滤器是Servlet规范规定的,仅用于Web程序中;拦截器是属于Spring容器内的,既可用于Web程序中,也可用于非Web程序中;
使用资源:由于拦截器是属于Spring容器内的,也是属于Spring的一个组件,它就可以使用Spring容器中的所有资源和对象;过滤器不可以;
深度不同:过滤器只作用在servlet前后;拦截器能够深入到方法执行前后、异常抛出前后等,拦截器具有更大的弹性。在实际开发过程中,我们应该优先选择使用拦截器;
2.过滤器的2种使用方式
第一种方式:利用WebFilter注解配置,启动类要结合@ServletComponentScan注解
package com.gui.star.web.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 利用WebFilter注解配置,启动类要结合@ServletComponentScan注解
*/
@WebFilter(filterName = "customFilter1", urlPatterns = "/*")
@Slf4j
public class CustomFilter1 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("CustomFilter1初始化...");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("doFilter in CustomFilter1请求处理....");
//对request、response进行一些预处理,比如设置请求编码
// request.setCharacterEncoding("UTF-8");
// response.setCharacterEncoding("UTF-8");
//TODO 进行业务逻辑
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
log.info("CustomFilter1销毁...");
}
}
注意:对于该种方式,如果有多个过滤器,我们就无法保证它们执行的先后顺序(可以按过滤器名称来区分,首字母从a-z的先后顺序执行)
第二种方式:FilterRegistrationBean
package com.gui.star.web.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import java.io.IOException;
@Slf4j
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("CustomFilter初始化...");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("doFilter in CustomFilter请求处理....");
//对request、response进行一些预处理,比如设置请求编码
// request.setCharacterEncoding("UTF-8");
// response.setCharacterEncoding("UTF-8");
//TODO 进行业务逻辑
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
log.info("CustomFilter销毁...");
}
}
package com.gui.star.web.config;
import com.gui.star.web.filter.CustomFilter;
import com.gui.star.web.filter.CustomFollowFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* 过滤器第二种使用方式配置
*/
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CustomFilter customFilter = new CustomFilter();
registrationBean.setFilter(customFilter);
registrationBean.setOrder(10);//设置过滤器执行的先后顺序,越小越优先执行
List<String> urlPatterns = new ArrayList<String>();
urlPatterns.add("/*");
registrationBean.setUrlPatterns(urlPatterns);
return registrationBean;
}
}
3.如何使用拦截器
package com.gui.star.web.interceptors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义拦截器(继承HandlerInterceptorAdapter类)
*/
@Configuration
@Slf4j
public class LogInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("请求前调用:preHandle" );
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("请求后调用:postHandle");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("请求调用完成后回调方法:afterCompletion");
super.afterCompletion(request, response, handler, ex);
}
}
package com.gui.star.web.config;
import com.gui.star.web.interceptors.LogInterceptor;
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;
/**
* 拦截器配置类(实现WebMvcConfigurer接口)
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
/**
* 注册自定义的拦截器类
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 加入自定义拦截器,这里可以根据实际需要对各个url添加不同的拦截器
registry.addInterceptor(logInterceptor).addPathPatterns("/**/**");
}
}