Zuul學習(三)——自定義參數解析器

1.我們在controller的方法經常要根據token來獲取用戶的信息,如果每個方法都執行這個操作讓程序看起來不太優雅,所以選擇使用自定義參數解析器去自動根據token獲取用戶信息,在controller的方法上加入這個對象作爲參數即可。

2.在common模塊編寫這個自定義參數解析器

@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz = methodParameter.getParameterType();
        return clazz == AuthenticationInfo.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String paramToken = request.getParameter("token");
        String cookieToken = getCookieValue(request, "token");
        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
            throw new GlobalException(500, "xxx");
        }
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        //TODO 根據token獲取用戶信息
        AuthenticationInfo authenticationInfo = new AuthenticationInfo();
        authenticationInfo.setId(1L);
        authenticationInfo.setName("張三");
        return authenticationInfo;
    }

    private String getCookieValue(HttpServletRequest request, String cookiName) {
        Cookie[]  cookies = request.getCookies();
        if(cookies != null && cookies.length > 0 ){
            for(Cookie cookie : cookies) {
                if(cookie.getName().equals(cookiName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private UserArgumentResolver userArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userArgumentResolver);
    }
}

3.在user-service引入common模塊之後,這樣操作就可以拿到當前用戶的信息

@RestController
public class ApiTestConroller {

    @GetMapping("/api/say")
    public String sayHi(AuthenticationInfo authenticationInfo) {
        return authenticationInfo.toString();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章