1

我可以通过这种方式将用户名从 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());
  ...
4

1 回答 1

4
#{sessionScope['username']}

这基本上打印了带有 name 的 session 属性"username"。原始 Java 代码中的内容类似于以下内容(如果您熟悉基本的Servlet API):

response.getWriter().print(session.getAttribute("username"));

如果这部分有效,那么您肯定根本没有使用容器管理的身份验证,因此容器管理的用户主体和用户角色获取器肯定不会返回任何内容。

您可以像访问会话范围的 JSF 托管 bean 一样访问会话属性(它们在幕后即也存储为会话属性!):

@ManagedProperty("#{username}")
private String username; // +setter

或者,当然,笨拙的方式:

String username = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("username");

也可以看看:


与具体问题无关:我非常怀疑那个隐藏的输入字段和那段 JS 的有用性。为什么要将服务器端已经存在的变量传递回服务器端?你确定你真的需要这样做吗?

于 2012-08-27T11:49:30.643 回答