gpt4 book ai didi

Java Web 应用程序 session 变量

转载 作者:搜寻专家 更新时间:2023-11-01 03:34:35 25 4
gpt4 key购买 nike

如何在当前用户登录后将其信息存储在 session 变量中?在他们登录后,需要在整个 Web 应用程序中访问此数据。

这是我目前所拥有的:

用户.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() {}
...

用户数据.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());
}

返回了正确的用户对象,但我不知道如何在用户 session 数据中保存用户对象。

我正在使用的技术(以防有帮助):

  • hibernate
  • MySQL
  • JPA
  • JSF
  • 野蝇

最佳答案

因为你的 User 类是由 @Named 注释管理的,你可以通过在你想使用它的类中注入(inject)它的实例来访问当前用户:

@Inject
private User user;

另一个解决方案是使用这样的代码:

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

关于Java Web 应用程序 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com