cookie和session案例

登录页面:login.jsp

  <body>
    <%--本页面提供登录表单,还要显示错误信息 --%>
    <h1>登录</h1>
    <%
     String uname ="";
     Cookie[] cs = request.getCookies();
     if(cs!=null){
      for(Cookie c:cs){
       if("uname".equals(c.getName()))
       {
        uname=c.getValue();
       }
      }
     }
    %>
    <%
     String message="";
     String msg = (String)request.getAttribute("msg");
     if(msg!=null){
      message = msg;
     }
    %>
    <font color="red"><b><%=message %></b></font>
    <form action="/hellosession1/LoginServlet" method="post">
     用户名:<input type="text" name="username" value="<%=uname%>"><br>
     密 码:<input type="password" name="password"><br>
     <input type="submit" value="登录">
    </form>
  </body>



servlet处理页面:LoginServlet.java

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //获取表单数据
  //处理编码问题
  request.setCharacterEncoding("UTF-8");
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  //校验用户名和密码是否正确
  if(!"itcast".equalsIgnoreCase(username)){//登陆成功
   
   Cookie cookie = new Cookie("uname",username);//获取cookie
   cookie.setMaxAge(60*60*24);
   response.addCookie(cookie);
   
   HttpSession session = request.getSession();//获取session
   session.setAttribute("username", username);//向session域中存username
   response.sendRedirect("/hellosession1/session2/succ1.jsp");
  }else{//登录失败
   //如果失败,保存到request域中,转发到login.jsp
   request.setAttribute("msg", "用户名或密码错误");
   request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
  }
  
 }



登录成功页面:succ1.jsp

  <body>
   <%
      String username = (String)session.getAttribute("username");
      if(username==null){
       request.setAttribute("msg", "您还没有登录,请先登录!");
       request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
       return;
      }
     %>
    <h1>登录成功</h1>
    欢迎回来<%=session.getAttribute("username") %>
  </body>

猜你喜欢

转载自blog.csdn.net/qq_37685457/article/details/78068526