我可以通过这种方式将用户名从 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
但用户始终为空.. 做错了什么?
更新(创建会话容器):
public String login() {
...
FacesContext context = FacesContext.getCurrentInstance();
session = (HttpSession) context.getExternalContext().getSession(true);
session.setAttribute("id", user.getId());
session.setAttribute("username", user.getName());
...