Login Page?
For my school project, I have to work on an app for students to vote for events in the school. With that, I need them to log in using their student numbers and password. Any idea how I could code that ? (Eclipse / MYSQL)
.
package Main;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class LoginFrame extends javax.swing.JFrame {
//Instance of frame
public static JFrame ctx;
public LoginFrame() {
initComponents();
ctx = this;
}
private void initComponents() {
username = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
login = new javax.swing.JButton();
password = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("School Login");
setBackground(new java.awt.Color(255, 255, 255));
username.setBackground(new java.awt.Color(240, 240, 240));
username.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
username.setMargin(new java.awt.Insets(2, 5, 2, 2));
jLabel1.setText("Student ID");
jLabel2.setText("Password");
login.setBackground(new java.awt.Color(76, 175, 80));
login.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N
login.setForeground(new java.awt.Color(255, 255, 255));
login.setText("Login");
login.setBorder(null);
login.setPreferredSize(new java.awt.Dimension(73, 30));
login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginActionPerformed(evt);
}
});
password.setBackground(new java.awt.Color(240, 240, 240));
password.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(username)
.addComponent(login, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
.addComponent(password))
.addContainerGap(170, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(146, 146, 146)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(160, Short.MAX_VALUE))
);
pack();
}
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
//Get the username and the password
String user = SQLEscape(username.getText());
String pass = SQLEscape(password.getText());
try {
//Create the Connection thread. (In a thread so it doesnt block UI)
new ConnectionThread(user, pass);
} catch (MalformedURLException ex) {
Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String SQLEscape(String str) {
String data = null;
if (str != null && str.length() > 0) {
str = str.replace("\\", "\\\\");
str = str.replace("'", "\\'");
str = str.replace("\0", "\\0");
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\r");
str = str.replace("\"", "\\\"");
str = str.replace("\\x1a", "\\Z");
data = str;
}
return data;
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton login;
private javax.swing.JPasswordField password;
private javax.swing.JTextField username;
// End of variables declaration
}
package Main;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.JOptionPane;
public class ConnectionThread extends Thread {
//Student Details to Check
private String StudentID;
private String Password;
private String TableName = "users";
/**
* CHANGE ALL OF THIS TO MATCH YOUR SETTINGS.
*/
private String userName = ""; //USERNAME
private String password = ""; //PASSWORD
private String dbms = "mysql"; //DB TYPE (MYSQL, DERBY)
private String serverName = "localhost";//SERVERNAME EX. (LOCALHOST, 127.0.0.0)
private int portNumber = 3306; //PORT TO DATABASE (DEFAULT 3306)
private String dbName = "school"; //NAME OF DATABASE SHOULD BE school
//Constructor
public ConnectionThread(String id, String pass) throws MalformedURLException {
//Set the Values and start the thread
this.StudentID = id;
this.Password = pass;
this.start();
}
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
if (this.dbms.equals("mysql")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + "://"
+ this.serverName
+ ":" + this.portNumber + "/" + dbName,
connectionProps);
} else if (this.dbms.equals("derby")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + ":"
+ this.dbName
+ ";create=true",
connectionProps);
}
return conn;
}
//Create the Dialog for valid or invalid id, pass
public void createPopup(boolean temp) {
if (temp) {
JOptionPane.showMessageDialog(LoginFrame.ctx,
"successfully Logged In!");
} else {
//custom title, error icon
JOptionPane.showMessageDialog(LoginFrame.ctx,
"Student ID or Password was Incorrect",
"Invalid",
JOptionPane.ERROR_MESSAGE);
}
}
//Run Method
//Add the override annotation (MPGH doesn't allow me to post links and the (at) symbol is apparently a link)
public void run() {
//Create the Quesry from the strings we have
String query = "SELECT * FROM " + TableName + " WHERE studentid = '" + StudentID + "' AND password = '" + Password + "'";
//Create connection and statement
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = getConnection();
stmt = con.createStatement();
ResultSet set = stmt.executeQuery(query);
createPopup(set.next());
} catch (Exception e) {
e.printStackTrace();
}
}
}
CREATE DATABASE school;
CREATE TABLE users(
`ID` INT NOT NULL,
`studentid` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
PRIMARY KEY (ID)
);