I'm able to pass the username from JSF to managed bean e.g. this way:
<script type="text/javascript" >
function onLoad(){
document.getElementById("form:user").value = "#{sessionScope['username']}";}
window.onload = onLoad;
</script>
<h:inputHidden id="user" value="#{bean.username}"/>
Is it possible to get it directly using Java method? I've tried something like:
public String getCurrentUserName()
{
String name = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
if (externalContext.getUserPrincipal() != null) {
name = externalContext.getUserPrincipal().getName(); // null
}
return name;
}
or:
facesContext.getExternalContext().getRemoteUser(); // null
facesContext.getExternalContext().isUserInRole("pps"); // null
But user is always null.. what am doing wrong?
UPDATE (creation a session container):
public String login() {
...
FacesContext context = FacesContext.getCurrentInstance();
session = (HttpSession) context.getExternalContext().getSession(true);
session.setAttribute("id", user.getId());
session.setAttribute("username", user.getName());
...