欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot通過參數(shù)注解自動獲取當(dāng)前用戶信息的方法

 更新時間:2024年03月12日 09:46:28   作者:寫程序的小熊貓  
這篇文章主要介紹了SpringBoot通過參數(shù)注解自動獲取當(dāng)前用戶信息的方法,文中使用HandlerMethodArgumentResolver 類來實現(xiàn)這個功能,并通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下

需求:通過注解實現(xiàn)自動獲取當(dāng)前用戶信息

思路:使用HandlerMethodArgumentResolver 類來實現(xiàn)這個功能;

這個接口有兩個方法,supportsParameter和resolveArgument。

  1. 方法supportsParameter返回值是boolean類型,它的作用是判斷Controller層中的參數(shù),是否滿足條件,滿足條件則執(zhí)行resolveArgument方法,不滿足則跳過。
  2. resolveArgument方法,它只有在supportsParameter方法返回true的情況下才會被調(diào)用。用于處理一些業(yè)務(wù),將返回值賦值給Controller層中的這個參數(shù)。

執(zhí)行流程

1.請求 ->
2.攔截器(獲取當(dāng)前用戶并放在UserContext中)->
3.Controller->參數(shù)解析器(檢測到參數(shù)中有設(shè)置的注解和參數(shù),則給參數(shù)賦值) ->
4.service中進(jìn)行使用當(dāng)前用戶信息

Controller

package com.haier.strategy.resolution.controller;

@Slf4j
@RestController
@RequestMapping("/api/v1/test")
@Tag(name = "測試")
public class TestController {

    @Autowired
    private TestService testService;



    /**
     * 測試
     *
     * @param name
     * @return
     */
    @Operation(summary = "測試,根據(jù)姓名獲取學(xué)生信息")
    @GetMapping("/getByName")
    public StudentVo getByName(@RequestParam("name") String name, @Parameter(hidden = true) @LoginUser UserBo userBo) {
        return testService.getByName(name, userBo);
    }

controller通過在參數(shù)中注明 @LoginUser UserBo userBo就可以實現(xiàn)在service中獲取當(dāng)前用戶信息

注解

/**
 * 標(biāo)記需要解析為用戶信息的參數(shù)
 *
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginUser {
    boolean required() default true;

}

用戶實體類

/**
 * @Description: 用戶實體類
 * @Version: V1.0
 */
@Schema(description = "用戶實體類")
@Data
public class UserBo {

    @Schema(description = "用戶姓名")
    private String userName;
    @Schema(description = "用戶工號")
    private String jobNo;

}

userContext


/**
 * 用戶上下文UTIL
 *
 */
public class UserContext {

    /**
     * User holder
     * 考慮 TransmittableThreadLocal
     */
    private static final TransmittableThreadLocal<UserBo> CURRENT_USER_HOLDER = new TransmittableThreadLocal<>();
    private static final TransmittableThreadLocal<String> CURRENT_AUTHORIZATION = new TransmittableThreadLocal<>();

    /**
     * 保存 session
     *
     */
    public static void saveUser(UserBo user) {
        CURRENT_USER_HOLDER.set(user);
    }

    /**
     * 保存authorization
     */
    public static void saveAuthorization(String authorization) {
        CURRENT_AUTHORIZATION.set(authorization);
    }

    /**
     * 獲取authorization
     */
    public static String getAuthorization() {
        return CURRENT_AUTHORIZATION.get();
    }

    /**
     * 刪除authorization
     */
    public static void removeAuthorization() {
        CURRENT_AUTHORIZATION.remove();
    }

    /**
     * 當(dāng)前用戶
     *
     */
    public static UserBo currentUser() {
        return CURRENT_USER_HOLDER.get();
    }

    /**
     * remove session
     *
     */
    public static void removeUser() {
        CURRENT_USER_HOLDER.remove();
    }
}

攔截器

@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    @Lazy
    private StrategyCommonClient strategyCommonClient;

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

        String token = request.getHeader(CommonConst.ACCESS_TOKEN);
        String authorization = request.getHeader(CommonConst.AUTHORIZATION);
        UserContext.saveAuthorization(authorization);
        String userCode = request.getHeader(CommonConst.USER_CODE);
        ResultBody<UserBo> userRes;
        try {
            //通過認(rèn)證服務(wù)獲取當(dāng)前用戶信息
            userRes = commonClient.getUserInfo(userCode, token);
        } catch (Exception e) {
            throw new Exception("get_user_info_fail");
        }
        if (userRes.getCode() != 200 || userRes.getData() == null) {
            throw new Exception("get_user_info_fail");
        }
        UserContext.saveUser(userRes.getData());
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
        UserContext.removeAuthorization();
    }
}


參數(shù)解析器

@Slf4j
@Component
public class LoginUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class) && parameter.getParameterType().isAssignableFrom(UserBo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return UserContext.currentUser();
    }
}

到此這篇關(guān)于SpringBoot通過參數(shù)注解自動獲取當(dāng)前用戶信息功能的文章就介紹到這了,更多相關(guān)SpringBoot參數(shù)注解獲取信息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論