2014-02-24 65 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)); 
        } 
      }