2014-02-24 89 views
0

我在arraylist中存儲了登錄的用戶名,而不是將arraylist放在會話中。每當用戶第一次登錄時,它都會打印用戶名,但刷新頁面時會出現相同的名稱是印刷兩次,但我只想要打印的用戶名只有一次,不管用戶多少次刷新頁面,請幫助在arraylist中存儲值並打印它

String username = request.getParameter("username"); 
      String password = request.getParameter("password"); 


HttpSession session = request.getSession(true); 

     session.setAttribute("username", username); 
     session.setAttribute("password", password); 
     response.setContentType("text/html");     
     ArrayList<user> users = (ArrayList<user>) sc 
         .getAttribute("users"); 

       if (users == null) { 
        System.out.println("loggedInUsers creates"); 
        users = new ArrayList<user>(); 

       } 
       users.add(new user(Name, U_ID, Pass)); 

       sc.setAttribute("users", users); 


       users = (ArrayList<user>) sc.getAttribute("users"); 

       for (int i = 0; i <= users.size() - 1; i++) { 
        user user = users.get(i); 
        out.println(user.getUserName()+ "<br>"); 
        //out.println("<br/>" + user.get(i)); 
       } 
+0

在ArrayList上使用contains()來檢查它是否已經有當前的userName。如果是,請不要添加,如果否,則添加。 – TheLostMind

+1

希望這將幫助你 [哈希映射] [1]:http://stackoverflow.com/questions/3640648/how-to-correctly-use-hashmap –

回答

2

使用HashMap,因爲它不允許重複,並且將替換原來的鑰匙新的那一個。

HashMap hm = new HashMap(); 

hm.put (U_ID, new user(Name, U_ID, Pass)); 
+0

先生可以ü請告訴我我該怎麼辦這........與散列圖 –

+0

我已經爲你添加了一些代碼。 –

0

我不知道你問什麼,但據我瞭解你的代碼如下更改,可以做你的programme.Let我知道,如果它幫助。

String username = request.getParameter("username"); 
    String password = request.getParameter("password"); 


    HttpSession session = request.getSession(true); 

      session.setAttribute("username", username); 
      session.setAttribute("password", password); 
      response.setContentType("text/html");     
      ArrayList<user> users = (ArrayList<user>) sc 
          .getAttribute("users"); 
      boolean shouldPrint = false; //declare this variable to check if printing of username is required 
        if (users == null) { 
         shouldPrint = true; //set this value to true to print username 
         System.out.println("loggedInUsers creates"); 
         users = new ArrayList<user>(); 

        } 
        users.add(new user(Name, U_ID, Pass)); 

        sc.setAttribute("users", users); 


        users = (ArrayList<user>) sc.getAttribute("users"); 

/**********As far as i understood your code.You need to set condition here to prevent twice printing of user name***********************************************/ 
      if(shouldPrint) 
       { 
        for (int i = 0; i <= users.size() - 1; i++) { 
         user user = users.get(i); 
         out.println(user.getUserName()+ "<br>"); 
         //out.println("<br/>" + user.get(i)); 
        } 
      }