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

しかし、ユーザーは常に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());
  ...
4

1 に答える 1

4
#{sessionScope['username']}

これは基本的に、名前が.のセッション属性を出力します"username"生のJavaコードでは次のようなものです(基本的なサーブレット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 に答える