Reputation: 55
I'm using JSF 2.0 framework and I need help. To put it as simple as I can, what I need is to get a user's username
and id and display it in the application I'm building.
This is my UserBean class:
@ManagedBean
@SessionScope
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String username;
private String password;
//getter and setter methods
At the index.xhtml
page, the user needs to enter the username and password in order to login(comparing values from database). When he does, I want to output his username and id on the next page and keep track of that throughout whole application.
Upvotes: 2
Views: 1942
Reputation: 1108782
Your UserBean
is already in the session scope. You don't need to "keep track" of it yourself at all. If you need to display the properties of an arbitrary JSF managed bean in the view, just access them in EL the usual way.
<p>Welcome, #{userBean.username}!</p>
If you need to inject it in other beans, because you need the user's information in postconstructor or (action)listener methods, then just use @ManagedProperty
.
@ManagedBean
@RequestScoped
public class OtherBean {
@ManagedProperty("#{userBean}")
private UserBean userBean; // +setter
// ...
}
Upvotes: 2
Reputation: 46418
as username and id are in the session scoped bean. you can get them from the session map like this.
page2.XHTML
<h:outputText value="#{page2Bean.uname}"/>
<h:outputText value="#{page2Bean.id}"/>
Page2Bean.java
@managedBean(name="page2Bean")
class Page2Bean {
private String uName;
private int id;
//getters and setters
public page2Bean() {
UserBean uBean = (UserBean) (FacesContext.getCurrentInstance().getExternalContext().getSessionMap()).get("userBean"));// get the UserBean which is in the session
this.uName= uBean.getUserName();
this.id= uBean.getId();
}
EDIT you get the session data (username and id in this case) in the constructor and assign them to your attributes which you use in your page2.xhtml
lemme know if it helps...
Upvotes: -1
Reputation: 9935
If you would like to get session data form page directly. Use as below.
<h:outputText value="#{sessionScope.UserBean.username}"/>
<h:outputText value="#{sessionScope.UserBean.id}"/>
Upvotes: 0