1
子屬性我現在有一個用戶對象:獲取會話從對象
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;
}
和登錄功能,即返回一個User對象:
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;
}
而在去年,一個處理表單並設置不同屬性的servlet:
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;
}
}
我想要做的,例如,顯示在網頁上,用戶有(用戶名,電子郵件等)的子值之一。但是,我不確定如何使用session.getAttribute,以及如何獲取tempUser.username。
在此先感謝。
哥哥....我不能夠感謝你。那裏真的很棒。我設法修復它,這要感謝你: 用戶tempUser =(用戶)session.getAttribute(「user」); out.print(tempUser.username); 再次,非常感謝你的兄弟,真的。 –
好極了。嘗試使用EL,因爲它現在被廣泛使用一天,如果可能的話嘗試切換到Restful webservices –
@WilliamPfaffe如果將User類存儲在會話中,則存在潛在的安全風險。一旦填充,密碼將始終可用。一旦用戶登錄,不再需要密碼。考慮從用戶類中刪除密碼屬性,或者至少在用戶登錄後將其刪除。 –