2016-01-28 259 views
4

如何在登錄後將當前用戶的信息存儲在會話變量中?該數據需要在整個Web應用程序可以訪問他們在登錄後Java Web應用程序會話變量

這是我到目前爲止有:

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()); 
} 

正確的用戶對象返回,但我不知道如何保存用戶會話數據中的用戶對象。

技術我使用(如果幫助):

  • 休眠
  • MySQL的
  • JPA
  • JSF
  • Wildfly
+0

它的web框架是你在用嗎? –

+0

@ redflar3我沒有使用Web框架,這是普通的javaEE。 – Warosaurus

回答

1

由於您的User類管理由@Named註釋通貨膨脹,你可以通過在類注射它的實例訪問當前用戶要使用它:

@Inject 
private User user; 

另一個解決方法是使用這樣的代碼:

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

您能否解釋一下使用'evaluateExpressionGet(...)'還是使用'context.getAttributes()。get(「user」)更好? – Warosaurus