2015-07-02 54 views
0

我正在嘗試基於檢票創建一個簡單的應用程序。我想在我的頁面上放置一個Panel,指示用戶是否已登錄。 不幸的是,我無法找到我的問題的一個工作示例:我想讓我的Label顯示用戶名,如果某人登錄並收到一條消息,如果沒有用戶登錄。 我想我錯過了一些東西。以正確的方式使用動態Wicket資源

這裏談到的代碼:

面板:

public class Header extends Panel { 

IModel<StringResourceModel> userNameModel = new LoadableDetachableModel<StringResourceModel>() { 

    @Override 
    protected StringResourceModel load() { 
     final User user = MySession.get().getAuthenticatedUser(); 
     if (user==null){ 
      return new StringResourceModel("username.noUser", Header.this , null); 
     }else{ 
      return new StringResourceModel("username.user", Header.this, Model.of(user)); 
     } 
    } 
}; 

public Header(final String id) { 
    super(id); 
} 

@Override 
protected void onInitialize() { 
    super.onInitialize(); 
    add(new Label("username", userNameModel)); 

} 

} 

屬性:

username.noUser=You are not logged in 
username.user=Welcome, ${name} 

標記:

<wicket:panel> 
    <wicket:label class="username" wicket:id="username" /> 
</wicket:panel> 

呈現的文本是

StringResourceModel [鍵:username.noUser,默認:null,則params:[]

的行爲很有道理。但是,我怎樣才能修復它,使所需的文字呈現?通話

IModel<String> userNameModel = new LoadableDetachableModel<String>() { 

    @Override 
    protected String load() { 
     final User user = MySession.get().getAuthenticatedUser(); 
     if (user==null){ 
      return new StringResourceModel("username.noUser", Header.this , null).getObject(); 
     }else{ 
      return new StringResourceModel("username.user", Header.this, Model.of(user)).getObject(); 
     } 
    } 
}; 

注到StringResourceModel#getObject()

回答

0

您應該從#load()方法返回字符串。

0

我不得不在wiki更深入地瞭解和選擇以下方法:

public class Header extends Panel { 

    private static class UserState { 
     private final String userLoggedIn; 
     private final User user; 


     public UserState(final User user) { 
      super(); 
      userLoggedIn = user==null?"noUser":"user"; 
      this.user = user; 
     } 
     public String getUserLoggedIn() { 
      return userLoggedIn; 
     } 
     public User getUser() { 
      return user; 
     } 

    } 

    IModel<UserState> userModel   = new LoadableDetachableModel<UserState>() { 

             @Override 
             protected UserState load() { 
              return new UserState(HouseSession.get() 
                .getAuthenticatedUser()); 
             } 
            }; 


    public Header(final String id) { 
     super(id); 
    } 

    @Override 
    protected void onInitialize() { 
     super.onInitialize(); 
     final StringResourceModel messageModel = new StringResourceModel("username.${userLoggedIn}", Header.this, userModel); 
     add(new Label("username", messageModel)); 
    } 

    @Override 
    protected void onDetach() { 
     super.onDetach(); 
     userModel.detach(); 
    } 

} 
相關問題