JAVA:如何存储已登录用户

huangapple go评论126阅读模式
英文:

JAVA: How to store logged in user

问题

我正在使用Eclipse进行学校Java项目,与MySql一起使用。我已经制作了登录界面,并根据数据库的用户表验证了凭据。现在我需要使用已登录用户的用户ID在多个JFrame中显示它。是否有一种方式可以将该用户ID存储在一种全局变量中,以便可以从系统的任何地方访问?该项目有一个始终打开的菜单栏表单,我可以在那里创建一个变量,并从任何表单访问它,但我认为这不是解决此问题的正确方法。

英文:

I'm working in a school Java project with MySql using Eclipse. I already did the login screen and validated the credentials against the DB´s users table. Now I need to use the userid of the logged in user to show it in several JFrames. Is there a way to store that userid in a type of global variable that can be accessed from anywhere in the system? The project has a Menu Bar form that is open all the time, I could create a varible there and access it from any form but I do not think that is the correct way of solving this issue.

答案1

得分: 0

你没有提供关于你正在使用的技术的任何信息。因此,我只能根据Java编程语言给出一个通用的答案。

您可以在任何类中放置一个静态变量。无论您创建多少个类的实例,该变量在内存中只会存在一次。甚至在没有实例的情况下也可以访问它。

示例:

public class GlobalData 
{
    public static String userName=null;
}

您可以在任何地方简单地访问成员变量:

GlobalData.userName="IronMan";
英文:

You did not provide any information about the technology which you are using. So I can only give a generic answer based on the Java programming language.

You can place a static variable in any of your classes. This variable will exist only once in memory regardless how many instances of the class you create. It is even accessible without having an instance.

Example:

public class GlobalData 
{
    public static String userName=null;
}

You can simply access the member variable everywhere:

GlobalData.userName="IronMan";

huangapple
  • 本文由 发表于 2020年10月21日 02:30:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64451304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定