2019独角兽企业重金招聘Python工程师标准>>>
声明注解
@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CurrentUser { }
声明生成自定义参数拦截器
@Slf4j
@Component
public class ArgumentResolverInterceptor implements HandlerInterceptor {
@Autowired
private AppUserService appUserService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
log.info("ArgumentResolverInterceptor.uri={}", request.getRequestURI());
String token = request.getHeader("app_session");
log.info("app_session={}", token);
// 真实环境,token解析
if (StringUtil.isNotNull(token)){
UserProfile userProfile = UamBizApi.getUserProfile(request);
if (null == userProfile) {
AppCommonUtil.forbidAccess(response, AjaxResponse.INVALID_TOKEN, "禁止访问,token已失效");
return false;
}
log.info("ArgumentResolverInterceptor.userProfile={}, {}, {}", userProfile.getUid(), userProfile.getUsername(), userProfile.getPhone());
String userId = userProfile.getUid();
// 放到request中,便于@CurrentUser获取
CurrentUserInfo currentUser = appUserService.getOne(userId);
log.info("ArgumentResolverInterceptor.currentUser={}", currentUser);
request.setAttribute("currentUser", currentUser);
log.info("ArgumentResolverInterceptor process complete"); return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}
声明自定义参数解析器
@Slf4j public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(CurrentUser.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndView, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object currentUserInfo = webRequest.getAttribute("currentUser", 0); if(null == currentUserInfo) log.warn("---------------用户未登录---------------"); return currentUserInfo; } }
让SpringMVC加载我们定义参数解析器
@Configuration public class AppWebMvcConfigurationSupport extends WebMvcConfigurationSupport { /** * Controller 方法参数注入 * @param argumentResolvers */ @Override public void addArgumentResolvers(ListargumentResolvers) { argumentResolvers.add(new CurrentUserArgumentResolver()); } /** * 注册拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry .addInterceptor(new ArgumentResolverInterceptor()) .addPathPatterns("/**"); } }
在controller中使用
@PostMapping("/car/save")
public AjaxResponse save(@CurrentUser CurrentUserInfo currentUser, @RequestBody CarSaveReq req) {
}