7 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果不想在controller拿到用戶(hù)信息傳到service層,直接在service層也是可以拿到的。
spring mvc在處理請(qǐng)求的時(shí)候,會(huì)把請(qǐng)求對(duì)象放到RequestContextHolder持有的ThreadLocal對(duì)象中,你可以去看看DispatcherServlet類(lèi)的源代碼。
在service層可以按照如下代碼獲取:
//獲取到當(dāng)前線(xiàn)程綁定的請(qǐng)求對(duì)象 HttpServletRequest?request?=?((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); //已經(jīng)拿到session,就可以拿到session中保存的用戶(hù)信息了。 ????????System.out.println(request.getSession().getAttribute("userInfo"));

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
設(shè)計(jì)不合理,用戶(hù)信息應(yīng)該在Controller層獲取,然后傳入Service層使用。

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
ShiroUser user = null;
if (req != null) {
user = (ShiroUser) req.getSession().getAttribute("currentUser");
}
所以你想再service層獲取的是request 對(duì)不對(duì)?。?/p>

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
SecurityContextHolder 可以處理登錄用戶(hù)的存取,
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
UsernamePasswordAuthenticationToken authentication = SecurityContextHolder.getContext().getAuthentication();

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
比較簡(jiǎn)單方法就是頁(yè)面直接將用戶(hù)信息傳入servlet然后顯示到頁(yè)面上
ActionContext.getContext().put("name", name);
${username }
添加回答
舉報(bào)