cookie和session

本文详细介绍了使用Java Web实现登录验证的过程,包括登录页面展示、servlet处理逻辑及登录成功后的页面显示等内容。通过示例代码,展示了如何利用Cookie和Session进行用户状态管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

登录页面: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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值