如何在会话变量登录后将当前用户的信息存储在会话变量中?这些数据需要在登录后在整个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());
}
返回了正确的用户对象,但我不知道如何在用户的会话数据中保存用户对象。
我正在使用的技术(如果有帮助):
答案 0 :(得分:1)
由于User
类由@Named
注释管理,因此只需在要使用它的类中注入其实例即可访问当前用户:
@Inject
private User user;
另一种解决方案是使用这样的代码:
FacesContext context = FacesContext.getCurrentInstance();
User user = context.getApplication().evaluateExpressionGet(context, "#{user}", User.class);