首页 > 编程语言 > SpringBoot之HandlerInterceptor拦截器的使用详解
2020
10-28

SpringBoot之HandlerInterceptor拦截器的使用详解

前言

平常项目开发过程中,会遇到登录拦截权限校验参数处理防重复提交等问题,那拦截器就能帮我们统一处理这些问题。

一、实现方式

1.1 自定义拦截器

自定义拦截器,即拦截器的实现类,一般有两种自定义方式:

定义一个类,实现org.springframework.web.servlet.HandlerInterceptor接口。

定义一个类,继承已实现了HandlerInterceptor接口的类,例如org.springframework.web.servlet.handler.HandlerInterceptorAdapter抽象类。

1.2 添加Interceptor拦截器到WebMvcConfigurer配置器中

自定义配置器,然后实现WebMvcConfigurer配置器。

以前一般继承org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter类,不过SrpingBoot 2.0以上WebMvcConfigurerAdapter类就过时了。有以下2中替代方法:

直接实现org.springframework.web.servlet.config.annotation.WebMvcConfigurer接口。(推荐)

继承org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport类。但是继承WebMvcConfigurationSupport会让SpringBoot对mvc的自动配置失效。不过目前大多数项目是前后端分离,并没有对静态资源有自动配置的需求,所以继承WebMvcConfigurationSupport也未尝不可。

 二、HandlerInterceptor 方法介绍

preHandle:预处理,在业务处理器处理请求之前被调用,可以进行登录拦截,编码处理、安全控制、权限校验等处理;

default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	return true;
}

postHandle:后处理,在业务处理器处理请求执行完成后,生成视图之前被调用。即调用了Service并返回ModelAndView,但未进行页面渲染,可以修改ModelAndView,这个比较少用。

default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
}

afterCompletion:返回处理,在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。已经渲染了页面。

default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
}

三、拦截器(Interceptor)实现

3.1 实现HandlerInterceptor

此拦截器演示了通过注解形式,对用户权限进行拦截校验。

package com.nobody.interceptor;

import com.nobody.annotation.UserAuthenticate;
import com.nobody.context.UserContext;
import com.nobody.context.UserContextManager;
import com.nobody.exception.RestAPIError;
import com.nobody.exception.RestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Slf4j
@Component
public class UserPermissionInterceptor implements HandlerInterceptor {

  private UserContextManager userContextManager;

  @Autowired
  public void setContextManager(UserContextManager userContextManager) {
    this.userContextManager = userContextManager;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) {

    log.info(">>> UserPermissionInterceptor preHandle -- ");

    if (handler instanceof HandlerMethod) {
      HandlerMethod handlerMethod = (HandlerMethod) handler;

      // 获取用户权限校验注解(优先获取方法,无则再从类获取)
      UserAuthenticate userAuthenticate =
          handlerMethod.getMethod().getAnnotation(UserAuthenticate.class);
      if (null == userAuthenticate) {
        userAuthenticate = handlerMethod.getMethod().getDeclaringClass()
            .getAnnotation(UserAuthenticate.class);
      }
      if (userAuthenticate != null && userAuthenticate.permission()) {
        // 获取用户信息
        UserContext userContext = userContextManager.getUserContext(request);
        // 权限校验
        if (userAuthenticate.type() != userContext.getType()) {
          // 如若不抛出异常,也可返回false
          throw new RestException(RestAPIError.AUTH_ERROR);
        }
      }
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) {
    log.info(">>> UserPermissionInterceptor postHandle -- ");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    log.info(">>> UserPermissionInterceptor afterCompletion -- ");
  }
}

3.2 继承HandlerInterceptorAdapter

package com.nobody.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Slf4j
@Component
public class UserPermissionInterceptorAdapter extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) {
    log.info(">>> UserPermissionInterceptorAdapter preHandle -- ");
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) {
    log.info(">>> UserPermissionInterceptorAdapter postHandle -- ");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    log.info(">>> UserPermissionInterceptorAdapter afterCompletion -- ");
  }
}

四、配置器(WebMvcConfigurer)实现

4.1 实现WebMvcConfigurer(推荐)

package com.nobody.config;

import com.nobody.context.UserContextResolver;
import com.nobody.interceptor.UserPermissionInterceptor;
import com.nobody.interceptor.UserPermissionInterceptorAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

  private UserPermissionInterceptor userPermissionInterceptor;

  private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter;

  private UserContextResolver userContextResolver;

  @Autowired
  public void setUserPermissionInterceptor(UserPermissionInterceptor userPermissionInterceptor) {
    this.userPermissionInterceptor = userPermissionInterceptor;
  }

  @Autowired
  public void setUserPermissionInterceptorAdapter(
      UserPermissionInterceptorAdapter userPermissionInterceptorAdapter) {
    this.userPermissionInterceptorAdapter = userPermissionInterceptorAdapter;
  }

  @Autowired
  public void setUserContextResolver(UserContextResolver userContextResolver) {
    this.userContextResolver = userContextResolver;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 可以添加多个拦截器,一般只添加一个
    // addPathPatterns("/**") 表示对所有请求都拦截
    // .excludePathPatterns("/base/index") 表示排除对/base/index请求的拦截
    // 多个拦截器可以设置order顺序,值越小,preHandle越先执行,postHandle和afterCompletion越后执行
    // order默认的值是0,如果只添加一个拦截器,可以不显示设置order的值
    registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**")
        .excludePathPatterns("/base/index").order(0);
    // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**")
    // .excludePathPatterns("/base/index").order(1);
  }

  @Override
  public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    resolvers.add(userContextResolver);
  }
}

4.2 继承WebMvcConfigurationSupport

package com.nobody.config;

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.WebMvcConfigurationSupport;

import com.nobody.interceptor.UserPermissionInterceptor;
import com.nobody.interceptor.UserPermissionInterceptorAdapter;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Configuration
public class WebAppConfigurerSupport extends WebMvcConfigurationSupport {

  @Autowired
  private UserPermissionInterceptor userPermissionInterceptor;

  // @Autowired
  // private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 可以添加多个拦截器,一般只添加一个
    // addPathPatterns("/**") 表示对所有请求都拦截
    // .excludePathPatterns("/base/index") 表示排除对/base/index请求的拦截
    registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**")
        .excludePathPatterns("/base/index");
    // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**")
    // .excludePathPatterns("/base/index");
  }
}

五、其他主要辅助类

5.1 用户上下文类

package com.nobody.context;

import com.nobody.enums.AuthenticationTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @Description 用户上下文
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Getter
@Setter
@ToString
public class UserContext {
  // 用户名称
  private String name;
  // 用户ID
  private String userId;
  // 用户类型
  private AuthenticationTypeEnum type;
}

5.2 校验访问权限注解

package com.nobody.context;

import com.nobody.enums.AuthenticationTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @Description 用户上下文
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Getter
@Setter
@ToString
public class UserContext {
  // 用户名称
  private String name;
  // 用户ID
  private String userId;
  // 用户类型
  private AuthenticationTypeEnum type;
}

5.3 用户上下文操作类

package com.nobody.context;

import com.nobody.enums.AuthenticationTypeEnum;
import com.nobody.exception.RestAPIError;
import com.nobody.exception.RestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description 用户上下文操作类
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Component
public class UserContextManager {

  private static final String COOKIE_KEY = "__userToken";

  // @Autowired
  // private RedisService redisService;

  /**
   * 获取用户上下文信息
   * 
   * @param request
   * @return
   */
  public UserContext getUserContext(HttpServletRequest request) {
    String userToken = getUserToken(request, COOKIE_KEY);
    if (!StringUtils.isEmpty(userToken)) {
      // 从缓存或者第三方获取用户信息
      // String userContextStr = redisService.getString(userToken);
      // if (!StringUtils.isEmpty(userContextStr)) {
      // return JSON.parseObject(userContextStr, UserContext.class);
      // }
      // 因为演示,没集成Redis,故简单new对象
      UserContext userContext = new UserContext();
      userContext.setName("Mr.nobody");
      userContext.setUserId("0000001");
      userContext.setType(AuthenticationTypeEnum.ADMIN);
      return userContext;
    }
    throw new RestException(RestAPIError.AUTH_ERROR);
  }

  public String getUserToken(HttpServletRequest request, String cookieKey) {
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
      for (Cookie cookie : cookies) {
        if (Objects.equals(cookie.getName(), cookieKey)) {
          return cookie.getValue();
        }
      }
    }
    return null;
  }

  /**
   * 保存用户上下文信息
   * 
   * @param response
   * @param userContextStr
   */
  public void saveUserContext(HttpServletResponse response, String userContextStr) {
    // 用户token实际根据自己业务进行生成,此处简单用UUID
    String userToken = UUID.randomUUID().toString();
    // 设置cookie
    Cookie cookie = new Cookie(COOKIE_KEY, userToken);
    cookie.setPath("/");
    response.addCookie(cookie);
    // redis缓存
    // redisService.setString(userToken, userContextStr, 3600);
  }

}

5.4 方法参数解析器类

package com.nobody.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 对有UserContext参数的接口,进行拦截注入用户信息
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Component
@Slf4j
public class UserContextResolver implements HandlerMethodArgumentResolver {

  @Autowired
  private UserContextManager userContextManager;

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
    log.info(">>> resolveArgument -- begin...");
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    // 从缓存获取用户信息赋值到接口参数中
    return userContextManager.getUserContext(request);
  }

  /**
   * 只对UserContext参数进行拦截赋值
   * 
   * @param methodParameter
   * @return
   */
  @Override
  public boolean supportsParameter(MethodParameter methodParameter) {
    if (methodParameter.getParameterType().equals(UserContext.class)) {
      return true;
    }
    return false;
  }
}

六、测试验证

package com.nobody.controller;

import com.alibaba.fastjson.JSON;
import com.nobody.annotation.UserAuthenticate;
import com.nobody.context.UserContext;
import com.nobody.context.UserContextManager;
import com.nobody.enums.AuthenticationTypeEnum;
import com.nobody.pojo.model.GeneralResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

  @Autowired
  private UserContextManager userContextManager;

  @GetMapping("login")
  public GeneralResult<UserContext> doLogin(HttpServletResponse response) {
    UserContext userContext = new UserContext();
    userContext.setUserId("0000001");
    userContext.setName("Mr.nobody");
    userContext.setType(AuthenticationTypeEnum.ADMIN);
    userContextManager.saveUserContext(response, JSON.toJSONString(userContext));
    return GeneralResult.genSuccessResult(userContext);
  }

  @GetMapping("personal")
  @UserAuthenticate(permission = true, type = AuthenticationTypeEnum.ADMIN)
  public GeneralResult<UserContext> getPersonInfo(UserContext userContext) {
    return GeneralResult.genSuccessResult(userContext);
  }
}

启动服务后,在浏览器先调用personal接口,因为没有登录,所以会报错没有权限:

在这里插入图片描述

控制台输出:

在这里插入图片描述

启动服务后,在浏览器先访问login接口进行登录,再访问personal接口,验证通过,正确返回用户信息:

在这里插入图片描述

在这里插入图片描述

七、Github项目

项目工程可从Github获取,https://github.com/LucioChn/springboot-common.git

到此这篇关于SpringBoot之HandlerInterceptor拦截器的使用详解的文章就介绍到这了,更多相关SpringBoot HandlerInterceptor拦截器内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧