问题
I am trying to populate a datatable in my jsf page. Here is what i do: I first add the user to the session who logins to the system in my LoginBean:
@ManagedBean(name = "loginBean")
@Dependent
@SessionScoped
public void loginCheck() {
Customer currentCustomer = new Customer(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7),accounts);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("currentCustomer", currentCustomer);
// I skipped username and password check from
// and getting customer information from database
// not to make the code too log, i do them in my project
}
Then i want to fill a datatable with current user's accounts information. Here is my Customer class's related parts:
@ManagedBean(name = "customer")
@SessionScoped
public class Customer implements Serializable {
private List<Account> accounts;
public void setAccounts(ArrayList<Account> accounts){
this.accounts=accounts;
}
public List<Account> getAccounts(){
return accounts;
}
And here is the jsf page i populate my data:
<h:form>
<h:dataTable id="accountsTable" value="#{customer.accounts}" var="account">
<h:column>
<f:facet name="header">Account Number</f:facet>
#{account.accountNumber}
</h:column>
</h:dataTable>
</h:form>
But the problem is, since i keep the customer in the session, value="#{customer.accounts}" returns null because it is really null. I somehow need to get the current session object. I tried:
value="#{FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentCustomer");}"
But it does not see the FacesContext() in a jsf page. I was thinking to get the customer object first, and then reach its accounts list, which is an ArrayList. So how can do this? Can anyone help?
Thanks
回答1:
You can get it via its key: #{currentCustomer}
, in EL context.
And for your information, both current faces context and session attribute map are available via implicit EL objects: #{facesContext}
and #{sessionScope}
respectively. The latter can of course be used to get the previously put object in session map as well.
Also it'd be wise to concentrate on JSF basics before moving on any further.
来源:https://stackoverflow.com/questions/17503839/how-to-get-and-use-a-session-object-to-populate-a-datatable-in-jsf