登录过后去到另一个界面(比如商品详情页面),一般是根据cookie中的token来获取用户信息,然后再将用户信息根据model.addAttribute()传入controller中。
这样做代码重复,我们利用HandlerMethodArgumentResolver来解决。
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
UserService userService;
/**
* 当参数类型为User才做处理
*
* @param methodParameter
* @return
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
//获取参数类型
Class<?> clazz = methodParameter.getParameterType();
return clazz == User.class;
}
/**
* 思路:先获取到已有参数HttpServletRequest,从中获取到token,再用token作为key从redis拿到User,而HttpServletResponse作用是为了延迟有效期
*/
@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(UserService.COOKIE_NAME_TOKEN);
String cookieToken = getCookieValue(request, UserService.COOKIE_NAME_TOKEN);
if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
return null;
}
String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
return userService.getByToken(response, token);
}
//遍历所有cookie,找到需要的那个cookie
private String getCookieValue(HttpServletRequest request, String cookiName) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length <= 0) {
return null;
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookiName)) {
return cookie.getValue();
}
}
return null;
}
}
还要自定义一个参数解析器,改变SpringMVC的Controller传入参数,实现可以User替换Token做为参数从登陆页面传到商品列表页面。
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
UserArgumentResolver userArgumentResolver;
/**
* SpringMVC框架回调addArgumentResolvers,然后给Controller的参数赋值
* @param argumentResolvers
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(userArgumentResolver);
}
}