Warosaurus
Warosaurus

Reputation: 530

Java Web application session variables

How can I store the information for the current user in a session variable once they have logged in? This data needs to be accessed throughout the web application after they have logged in.

This is what I have so far:

User.java

@Named
@Table
@Entity
@SessionScoped
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "firstname")
    private String firstname;

    @Column(name = "lastname")
    private String lastname;

    @Column(name="username")
    private String username;

    @Column(name = "password")
    private String password;

    public User() {}
...

UserData.java

@Named
@RequestScoped
public class UserData implements Serializable {

    private static final long serialVersionUID = 1L;
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;
    List<User> users;
    String username;
    String password;

    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public UserData() {
        try {
            this.session = sessionFactory.openSession();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

public void login() {
    System.out.println("Authorize: Username: " + this.username + " Password: " + this.password);

    Query query = session.createQuery("from User U where U.username = :username and U.password = :password");
    query.setParameter("username", this.username);
    query.setParameter("password", this.password);
    System.out.println(query.list());
}

The correct user object is returned but I have no idea how to save the user object within the user's session data.

Technologies I am using (in case that helps):

Upvotes: 4

Views: 970

Answers (1)

Patrick
Patrick

Reputation: 831

Since your User class is managed by the @Named annotation, you can access the current user just by injecting its instance in the class you want to use it :

@Inject
private User user;

An other solution is to use a code like this :

FacesContext context = FacesContext.getCurrentInstance();
User user = context.getApplication().evaluateExpressionGet(context, "#{user}", User.class);

Upvotes: 1

Related Questions