- 在参数前加上对应的注解,就可以获得解析后的参数,因此在需要解析参数的方法上加上注解
//在需要获得解析参数前加上注解,例如@CurrentUserId
public ResponseResult findAll(@CurrentUserId String userId){
System.out.println(userId);
}
- 在cxsbg包下新建resovler包,在resolver包中定义第一步中的注解
package com.cxsbg.resolver;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER) //定义注解可以用在哪里,例如方法参数上
@Retention(RetentionPolicy.RUNTIME)//定义注解可以用在什么时候,比如runtime
public @interface CurrentUserId {
}
- 配置参数解析器,在config包下新建ArgumentResolverConfig,实现WebMvcConfigurer中的参数解析方法
package com.cxsbg.config;
import com.cxsbg.resolver.UserIdArgumentResolver;
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.WebMvcConfigurer;
import java.util.List;
@Configuration //表示这是配置
public class ArgumentResolverConfig implements WebMvcConfigurer {
@Autowired
private UserIdArgumentResolver userIdArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(userIdArgumentResolver);
}
}
- 实现自己的参数解析方法,在resolver包下新建UserIdArgumentResolver 类
package com.cxsbg.resolver;
import com.cxsbg.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class UserIdArgumentResolver implements HandlerMethodArgumentResolver {
//判断方法参数有没有加上CurrentUserId注解,如果有就会进行解析
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(CurrentUserId.class);
}
//自定义的参数解析方法,解析后的结果返回,会赋值到加了CurrentUserId注解的参数上
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//获取请求头的token
String token = webRequest.getHeader("token");
if(StringUtils.hasText(token)){
//解析token,获得userId
Claims claims = JwtUtil.parseJWT(token);
String userId = claims.getSubject();
return userId;
}
return null;
}
}