您好,登錄后才能下訂單哦!
本篇文章為大家展示了Springboot中怎么通過自定義HandlerMethodArgumentResolver獲取當(dāng)前登陸者,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
Springboot版本是2.0.5.release。
一般在controller方法中要獲取當(dāng)前登陸者,我們可以自定義HandlerMethodArgumentResolver來實(shí)現(xiàn),如下:
List-1
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface LoginUser { } ... public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterType().isAssignableFrom(UserVo.class) && methodParameter.hasParameterAnnotation(LoginUser.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { return SpringHelper.getLoginUser(); } } ... @Configuration public class WebSecurityConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new LoginUserHandlerMethodArgumentResolver()); } ... public class SpringHelper { public static HttpServletRequest getCurrentRequest() { HttpServletRequest request = null; try { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (null==requestAttributes){ return null; } request = ((ServletRequestAttributes)requestAttributes ).getRequest(); } catch (Exception e) { return request; } return request; } public static UserVo getLoginUser() { return (UserVo) getCurrentRequest().getSession().getAttribute(WebSecurityConfig.SESSION_KEY); } }
List-2
public List<PasgrInfoFlightVo> queryIDInfo(@LoginUser UserVo userVo) throws AicException { ... }
List-1中,我們自定義了LoginUserHandlerMethodArgumentResolver,方法supportsParameter返回true標(biāo)示支持此參數(shù)的解析,之后會(huì)調(diào)用resolveArgument進(jìn)行參數(shù)的解析。
List-2中,我們直接在controller的方法上加上@LoginUser注解,之后Spring會(huì)自動(dòng)將userVo傳入。
上述內(nèi)容就是Springboot中怎么通過自定義HandlerMethodArgumentResolver獲取當(dāng)前登陸者,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。