在arraylist中存储值并打印它

时间:2014-02-24 08:36:53

标签: java jsp arraylist servlet-3.0

我将登录的用户名存储在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));
              } 

2 个答案:

答案 0 :(得分:2)

使用Hashmap,因为它不允许重复,并将原始密钥替换为新密钥。

HashMap hm = new HashMap();

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

答案 1 :(得分:0)

我不确定你要求的是什么,但据我所知,您的代码可能会对您的程序进行更改。让我知道它是否有帮助。

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));
                  } 
             }