I currently have a User object:
public class User {
public final String username, password, email;
public final double balance;
public User(String username, String password, String email, double balance) {
this.username = username;
this.password = password;
this.email = email;
this.balance = balance;
}
And a login function, that returns a User object:
public User checkLogin(String usrname, String pssword) {
Front fr = new Front();
User newUser = null;
try {
int count = 0;
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/projects", "william", "william");
java.sql.Statement mySt = myConn.createStatement();
String rs = "SELECT username, password, email, balance FROM user WHERE username='" + usrname + "'AND password='" + pssword + "'";
System.out.println(rs);
ResultSet myRS = mySt.executeQuery(rs);
while (myRS.next()) {
newUser = new User(myRS.getString("username"),myRS.getString("password"),myRS.getString("email"),myRS.getDouble("balance"));
count++;
}
if (count == 0) {
return newUser;
}
if (count == 1) {
return newUser;
}
myConn.close();
} catch (SQLException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return newUser;
}
And last, a servlet, which handles forms, and sets different attributes:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Double balance = 0.00;
String origin = request.getParameter("origin");
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
switch(origin){
case "login":
db.checkLogin(username, password);
User tempUser;
if((tempUser = db.checkLogin(username, password)) != null){
out.print("You will be redirected");
request.getSession().setAttribute("user", tempUser);
response.sendRedirect("index.jsp");
}else if(db.checkLogin(username,password) == null){
out.print("Wrong login info, please try again!");
response.sendRedirect("login.jsp");
}
break;
case "register":
db.registerUser(username, password, balance, email);
response.sendRedirect("login.jsp");
break;
}
}
What I am trying to do, is for example, display on a webpage, one of the sub-values that User has (username, email and so on). However, I am unsure howto use session.getAttribute, and how I can get tempUser.username out.
Thanks in advance.