15-springboot向请求中添加内容

1 创建模块,添加依赖库,修改pom.xml


  
         org.springframework.boot
         spring-boot-starter-web
   

2 创建自定义注解,用于接收数据

import java.lang.annotation.*;

@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserInfo {
}

3 创建基于WebMvcConfigurationSupport的配置类

import com.vanpeng.webuser.handler.UserInfoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Configuration
public class UserInfoWebconfig extends WebMvcConfigurationSupport {
    @Override
    protected void addArgumentResolvers(List argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new UserInfoInterceptor());
    }
}

4 创建句柄方法解析器

import com.vanpeng.api.user.entity.RestSysUserVO;
import com.vanpeng.api.user.feign.UserApi;
import com.vanpeng.common.entity.Result;
import com.vanpeng.webuser.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
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;
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerMethodArgumentResolver {
    @Autowired
    private UserApi userApi;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if(methodParameter.hasParameterAnnotation(UserInfo.class))
            return true;
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
//        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//        String channel = request.getHeader("channel");
        RestSysUserVO userInfo = null;
        if(ObjectUtils.isEmpty(userApi)){
            return null;
        }
        //获取当前登录用户
        Result currentUserRes = userApi.getCurrentUser();
        if(ObjectUtils.isEmpty(currentUserRes)||currentUserRes.getCode()!=200){
            return null;
        }
        userInfo=currentUserRes.getData();
        log.info("拦截器中用户:",userInfo.getUsername());
        return userInfo;
    }
}

5 在自定义控制器中添加@UserInfo RestSysUserVO接收发送的对象

你可能感兴趣的:(15-springboot向请求中添加内容)