JSFからマネージドBeanにユーザー名を渡すことができます(例:次のように)。
<script type="text/javascript" >
function onLoad(){
document.getElementById("form:user").value = "#{sessionScope['username']}";}
window.onload = onLoad;
</script>
<h:inputHidden id="user" value="#{bean.username}"/>
Javaメソッドを使用して直接取得することは可能ですか?私は次のようなことを試しました:
public String getCurrentUserName()
{
String name = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
if (externalContext.getUserPrincipal() != null) {
name = externalContext.getUserPrincipal().getName(); // null
}
return name;
}
また:
facesContext.getExternalContext().getRemoteUser(); // null
facesContext.getExternalContext().isUserInRole("pps"); // null
しかし、ユーザーは常にnullです..何が間違っているのですか?
UPDATE(セッションコンテナの作成):
public String login() {
...
FacesContext context = FacesContext.getCurrentInstance();
session = (HttpSession) context.getExternalContext().getSession(true);
session.setAttribute("id", user.getId());
session.setAttribute("username", user.getName());
...