拦截器和过滤器的区别
过滤器和拦截器的区别:
①原理不同:拦截器是基于java的反射机制的,而过滤器是基于函数回调。
②使用范围不同:拦截器依赖于spring容器,可以单独使用;而过滤器依赖于tomcat容器,只能用于web程序。
③拦截请求范围不同:拦截器只能对controller中的请求或static静态资源目录下的请求起作用,而过滤器则可以对几乎进入容器的所有的请求起作用。
④注入bean情况不同:使用service层的bean时,需要在配置类中通过@Bean注解将其手动注册为bean,或通过@Resource注解注入该拦截器实例;而过滤器可以直接注入。
⑤触发时机不同:拦截器在servlet后。过滤器在servlet前。
自定义过滤器:
1.实现filter接口自定义过滤器
实现filter接口自定义过滤器:
@Component
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter 前置");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("Filter 处理中");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("Filter 后置");
}
}
2.瑞吉外卖实例
//瑞吉外卖校验登录状态过滤器:
/*检查用户是否已完成登录*/
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
//路径匹配器,支持通配符
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//1.获取本次请求的uri
String requestURI = request.getRequestURI();
log.info("1.拦截到请求:{}",requestURI);
//定义不需要处理的请求路径
String[] urls = new String[]{
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**",
"/common/**",
"/user/sendMsg",
"/user/login"
};
//2.判断本次请求是否需要处理
boolean check=check(urls,requestURI);
//3.若不需要处理,则直接放行
if (check){
log.info("3.本次请求{}不需要处理",requestURI);
filterChain.doFilter(request,response);
return;
}
//4-1.判断登录状态,若已登录则直接放行
if (request.getSession().getAttribute("employee")!=null){
log.info("4.用户已登录,用户id为:{}",request.getSession().getAttribute("employee"));
Long empId=(Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
long id = Thread.currentThread().getId();
log.info("线程id为{}",id);
filterChain.doFilter(request,response);
return;
}
//4-2.判断移动端用户登录状态,若已登录则直接放行
if (request.getSession().getAttribute("user")!=null){
log.info("4.用户已登录,用户id为:{}",request.getSession().getAttribute("user"));
Long userId=(Long) request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
long id = Thread.currentThread().getId();
log.info("线程id为{}",id);
filterChain.doFilter(request,response);
return;
}
//5.若未登录,则返回未登录的结果,通过输出流方式向客户端响应数据
log.info("5.用户未登录");
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/*路径匹配,检查本次请求是否需要放行*/
public boolean check(String[] urls,String requestURI) {
for (String url:urls){
boolean match=PATH_MATCHER.match(url,requestURI);
if (match){
return true;
}
}
return false;
}
}
自定义拦截器
1.实现HandlerInterceptor接口自定义拦截器
1.有多个拦截器时,越先声明的拦截器preHandle越先执行,postHandle和afterCompletion越后执行。
2.preHandle在请求处理前执行,postHandle在视图渲染前执行,afterCompletion在请求完成后执行。
3.拦截器默认的执行顺序,就是它的注册顺序,也可以通过Order手动设置控制,值越小越先执行。
//实现HandlerInterceptor接口自定义拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor 前置");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor 处理中");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor 后置");
}
}
2.配置类注册拦截器
在配置类中实现WebMvcConfigurer接口,重写addInterceptors方法,
注册拦截器,并添加或排除拦截路径。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
}
}
3.黑马点评实例
//刷新拦截器1
public class RefreshTokenInterceptor implements HandlerInterceptor {
private StringRedisTemplate stringRedisTemplate;
public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
this.stringRedisTemplate=stringRedisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//todo 1.获取请求体中的token
String token = request.getHeader("authorization");
if (StrUtil.isBlank(token)) {
return true;
}
//todo 2.基于token获取redis中的用户
String key = LOGIN_USER_KEY + token;
Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
// stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
//3.判断用户是否存在
if (userMap.isEmpty()) {
//直接放行
return true;
}
//5.todo 将查询到的hash数据转换为userdto
UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
//6.todo 存在,保存用户信息到ThreadLocal
UserHolder.saveUser(userDTO);
//7.todo 刷新token有效期
stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
//8.放行
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//移除用户
UserHolder.removeUser();
}
}
//自定义拦截器2
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断是否需要去拦截(threadlocal中是否有用户)
if (UserHolder.getUser()==null){
//没有,需要拦截,设置状态码401
response.setStatus(401);
return false;
}
//有用户,放行
return true;
}
}
//配置类注册拦截器
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/*解决拦截器中无法使用service
@Bean
public LoginInterceptor getLoginInterceptor(){
return new LoginInterceptor();
}*/
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加登录拦截器
registry.addInterceptor(new LoginInterceptor())
.excludePathPatterns(
"/shop/**","/shop-type/**","/voucher/**","/blog/hot",
"/user/code","/user/login")
.order(1);//值越大,优先级越低
//添加token刷新拦截器
registry.addInterceptor(newRefreshTokenInterceptor(stringRedisTemplate)).order(0);
}
}