Zuul学习(三)——自定义参数解析器
1.我们在controller的方法经常要根据token来获取用户的信息,如果每个方法都执行这个操作让程序看起来不太优雅,所以选择使用自定义参数解析器去自动根据token获取用户信息,在controller的方法上加入这个对象作为参数即可。
2.在common模块编写这个自定义参数解析器
@Servicepublic 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;
}
}
@Configurationpublic class WebConfig implements WebMvcConfigurer {
@Autowired
private UserArgumentResolver userArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(userArgumentResolver);
}
}
3.在user-service引入common模块之后,这样操作就可以拿到当前用户的信息
@RestControllerpublic class ApiTestConroller {
@GetMapping("/api/say")
public String sayHi(AuthenticationInfo authenticationInfo) {
return authenticationInfo.toString();
}
}
以上是 Zuul学习(三)——自定义参数解析器 的全部内容, 来源链接: utcz.com/z/518663.html