1. 程式人生 > >使用自定義註解實現登入使用者獲取

使用自定義註解實現登入使用者獲取

  • 業務功能場景
    • 在程式碼程式中很多介面的呼叫會有限制,需要使用者在登入狀態下才能進行操作(需要眾多使用者的資訊等),這裡就使用註解在呼叫介面的時候進行驗證攔截。

自定義一個註解

package com.timothy.annotation;

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)
public @interface LoginUser {
    
}

定義一個類去實現 HandlerMethodArgumentResolver 並重寫其方法

package com.timothy.annotation.support;

import com.timothy.annotation.LoginUser;
import org.springframework.core.MethodParameter;
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;

/**
 *
 *
 */
public class LoginUserHandlerMethodArgumentResolver implements
        HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "X-Login-Token";


    /**
     * 判斷是否支援要轉換的引數型別
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(Integer.class)&&methodParameter.hasParameterAnnotation(LoginUser.class);
    }

    /**
     * 當支援後進行相應的轉換 做業務操作
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest request,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //從請求頭中獲引數資訊
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if(token == null || token.isEmpty()){
            return "引數缺少token";
        }
        //若存在token可以從 redis 或 自定義的工具類中獲取userId(必須返回值與使用註解引數同類型)
        return 1;
    }
}

自定義一個配置類把上述交給spring管理

package com.timothy.config;

import com.timothy.annotation.support.LoginUserHandlerMethodArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * Created by wo on 2018/9/17.
 */
@Configuration
public class UserConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new LoginUserHandlerMethodArgumentResolver());
    }

}

在controller中使用即可

    @PostMapping("/add")
    public String loginInterface(@LoginUser Integer userId){
        //註解返回userId
        return "success";
    }