cookie和session的練習小Demo(用戶登錄)

1 、用戶類 (bean)html

   User (username  ,  password)數據庫

2 、模仿數據庫 (UserDb ) :建立一個list集合,在靜態代碼塊(程序運行時就加載)中添加對象,並建立方法判斷登陸session

private  static  List<User>  lists=new ArrayList<User>();post

    staticspa

    {orm

        list . add(new  User("zhangsan","123456"));htm

     }對象

public  static  User  login(String  name,String password)get

{input

    for(User  user : list)

    if(user.getname().equals(user.getpassword))

    {  return  user;  }

        return  null ;

}

三、(登陸界面) LoginUIServlet

   response.setContentType("text/html;charset=UTF-8");
   PrintWriter out = response.getWriter();
   out.println("<h1>登陸</h1>");
   out.println("<form method='post' action='"+request.getContextPath()+"/servlet/LoginServlet'>");  
   out.println("用戶名:<input type='text' name='username'/><br />");
   out.println("密碼:<input type='password' name='userpassword'/><br />");
   out.println("<input type='submit' value='登陸' /><br />");
   out.println("</form>");

四、判斷登陸界面中輸入的用戶名和密碼錯誤,跳到的界面

   response.setContentType("text/html;charset=UTF-8");
   PrintWriter out = response.getWriter();
   String username = request.getParameter("username");
   String password = request.getParameter("password");
  //判斷是否用戶名和密碼正確
  User user = UserDB.login(username, password);
  //用戶名或者密碼錯誤
 if(user == null)

 {
   out.println("用戶名或者密碼錯了,2秒後跳轉至登陸頁");
   response.setHeader("Refresh", "2;URL=" + request.getContextPath() + "/servlet/LoginUIServlet");
   return;
  }

//獲取session對象
  HttpSession session = request.getSession();
  session.setAttribute("user", user);
  //跳轉到首頁,用轉發仍是重定向?
  response.sendRedirect(request.getContextPath() + "/servlet/IndexServlet");

5 、首頁 (IndexServlet)

      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();
  //獲取sesison對象
      HttpSession session = request.getSession();
  //獲取session域中的user對象
      User user = (User)session.getAttribute("user");
  //直接跑到首頁,並未登陸的永恆
  if(user == null)

 {       out.println("您還未登陸,請先登陸,2秒後跳轉至登陸頁面");       response.setHeader("Refresh","2;URL=" + request.getContextPath() + "/servlet/LoginUIServlet");       return;  }  //登陸成功,有用戶對象      out.println("歡迎" + user.getUsername() + "登陸!");      out.println("<a href='"+request.getContextPath()+"/servlet/LogoutServlet'>註銷</a>"); }

相關文章
相關標籤/搜索