2010-09-03 69 views

回答

10

使用authentication tag

這個標籤允許訪問存儲在 安全上下文當前 認證對象。它直接在 JSP中呈現對象的 屬性。因此,舉例來說,如果認證的主要 屬性是Spring Security的 的UserDetails的 對象實例,然後使用 <秒:認證 屬性=「principal.username」/>將 呈現當前用戶的名稱。

當然,它是沒有必要使用 JSP標籤這種東西和 有些人喜歡保持儘可能少 邏輯儘可能在視圖中。您可以 訪問在 你的MVC控制器的認證對象(通過調用 SecurityContextHolder.getContext()。getAuthentication()) 和直接的數據添加到您的 模型由視圖渲染。

3

我假設你正在使用彈簧安全。後成功登錄把UserDetails對象中,像這樣的會議(這通常是控制器,其中,如果登錄爲全成,你會向前)

Object principal = SecurityContextHolder.getContext() 
    .getAuthentication().getPrincipal(); 
HttpSession session = request.getSession(true); //create a new session 

// put the UserDetails object here. 
session.setAttribute("userDetails", principal); 

在你的JSP可以訪問UserDetails對象,像這樣:

<span class="message">Welcome ${userDetails.username}</span>