JAVA在类之间传递值
给定一个需要用户输入两个信息的登录窗口:username&;暗语 成功识别后,用户将被重定向到主窗口。 在这里,我想显示他或她的用户名,但我收到空
这是我当前的代码: 登录类别:
private void LoginUser(String username, String password)
{
user = username;
pass = password;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = MainEngine.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT username FROM users WHERE username ='"+user+"' AND password ='"+getMD5Hex(pass)+"'");
if(rs.next()) // Successful login
{
Window_AfterLogin window_afterlogin = new Window_AfterLogin();
window_afterlogin.setVisible(true);
this.dispose();
}
else
{
label_info.setText("Wrong credentials");
}
}
catch(Exception e)
{
System.err.println(e);
}
}
public String getUserName()
{
return user;
}
注意:user和pass变量是全局变量
Window\u AfterLogin类:
public Window_AfterLogin() {
initComponents();
Window_Login window_login = new Window_Login();
System.out.println(window_login.getUserName());
}
# 1 楼答案
您的
Window_AfterLogin()
构造函数初始化另一个Window_Login
,这意味着存在用户名,您尝试通过window_login.getUserName()
-null
检索该用户名在登录后的代码中,您可以添加另一个字段
username
:在
LoginUser
类中,您必须相应地更改代码:注意:
您的应用程序易受SQL注入攻击。请阅读准备好的语句以及SQL注入在理论上是如何工作的,并尝试阻止它们
https://de.wikipedia.org/wiki/SQL-Injection https://www.tutorialspoint.com/javaexamples/jdbc_prepared_statement.htm
# 2 楼答案
在构造函数中,您正在创建Window_登录类的新实例,而不是设置用户名