2013-08-07 57 views
-1

我想輸出Username如果他登錄 從@Controller我有機會:接取從JSP用戶名中使用Spring Security的

@RequestMapping("/success") 
    public String success(Model model) { 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     String name = auth.getName(); //get logged in username 
     model.addAttribute("name", name); 
     return "success"; 
    } 

它工作的,如果我在JSP中使用的名字,我看到鍵入名稱。

但是,如果在這個JSP我寫

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> 
    <sec:authentication property="principal.username"/> 

我得到堆棧跟蹤:

INFO : com.epam.hhsystem.util.CustomAuthentificationProvider - User with name 'Nikolay_Tkachev' log in 
07.08.2013 17:00:57 org.apache.jasper.compiler.TldLocationsCache tldScanJar 
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 
07.08.2013 17:00:57 org.apache.catalina.core.ApplicationDispatcher invoke 
SEVERE: Servlet.service() for servlet jsp threw exception 
org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.username' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.username' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? 
    at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707) 
    at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:699) 

...

回答

9

當你使用的用戶名和密碼,使用具有authentiucation,主要是它的自我用戶的名字。嘗試使用

<sec:authentication property="principal"/> 
+0

爲什麼無處不在寫? – user2645679

+1

AFAIK,如果你有一個簡單的用戶名和密碼,用戶名可以作爲一個字符串直接存儲在principal中。但是,如果您有用戶名等公司名稱,部門等額外詳細信息,則可以將自定義對象分配給委託人,因此在這種情況下,您將使用委託人,用戶名 – coder

相關問題