Java 获取当前用户信息代码解析
这段代码用于获取当前用户的信息。
首先,通过 'RequestContextHolder.getRequestAttributes()' 方法获取请求属性,然后将其转换为 'ServletRequestAttributes' 类型,并获取其中的 'HttpServletRequest' 请求对象。
接着,通过 'HttpServletRequest::getUserPrincipal' 方法获取用户主体信息,如果存在则获取当前用户的名称,通过 'getCurrentUser' 方法获取当前用户的详细信息。如果不存在当前用户,则抛出异常 'I18nBizException',并指定错误代码 'CUR_USER_NOT_FOUND'。最终返回一个 'Optional' 对象,该对象可能为空,也可能包含当前用户的信息。
代码解析:
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.map(o -> (ServletRequestAttributes) o)
.map(ServletRequestAttributes::getRequest)
.map(HttpServletRequest::getUserPrincipal)
.map(principal -> getCurrentUser(principal.getName()))
.orElseThrow(() -> new I18nBizException(ErrorCode.User.CUR_USER_NOT_FOUND));
代码说明:
- 'RequestContextHolder.getRequestAttributes()':获取请求属性。
- '.map(o -> (ServletRequestAttributes) o)':将请求属性转换为 'ServletRequestAttributes' 类型。
- '.map(ServletRequestAttributes::getRequest)':获取 'HttpServletRequest' 请求对象。
- '.map(HttpServletRequest::getUserPrincipal)':获取用户主体信息。
- '.map(principal -> getCurrentUser(principal.getName()))':如果存在用户主体信息,则获取当前用户的名称,并通过 'getCurrentUser' 方法获取当前用户的详细信息。
- '.orElseThrow(() -> new I18nBizException(ErrorCode.User.CUR_USER_NOT_FOUND))':如果不存在当前用户,则抛出异常 'I18nBizException',并指定错误代码 'CUR_USER_NOT_FOUND'。
- 'Optional.ofNullable(...)':用于处理可能为空的值,如果为空则返回空 'Optional' 对象。
总结:
这段代码利用 'RequestContextHolder' 和 'Optional' 等工具,安全地获取当前用户的信息,并处理用户不存在的情况,保证代码的健壮性和可读性。
原文地址: https://www.cveoy.top/t/topic/ot2a 著作权归作者所有。请勿转载和采集!