使用Session实现登录用户保存

本文介绍如何在Java Servlet应用中利用Session技术来管理登录用户的会话状态,确保用户在登录后的操作安全性。
<%--
  Created by IntelliJ IDEA.
  User: 何
  Date: 2023/6/9
  Time: 9:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>管理员首页</title>
</head>
<body>
<%
    String admin = request.getParameter("admin");  //获取页面的数据
    String pswd = request.getParameter("pswd");
    if ("admin".equals(admin) && "admin".equals(pswd)) {

        session.setAttribute("admin", admin);
        session.setAttribute("pswd", pswd);
        session.setMaxInactiveInterval(10*60);  //设置有效时间
        %>
<h1>管理员首页</h1>
<%
    }else {
        out.print("用户名或密码错误!");
        response.setHeader("refresh","3;index.jsp");
    }
%>
<%
    String  userName = (String) session.getAttribute("admin");
    String  mima = (String) session.getAttribute("pswd");
    if (null==userName){
        response.sendRedirect("index.jsp");
        return;
    }else {
        out.print("欢迎你"+userName+"密码"+mima);
    }
%>
</body>
</html>

用户登录

<%--
  Created by IntelliJ IDEA.
  User: 何
  Date: 2023/6/9
  Time: 9:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <script type="text/javascript">
    function x() {
      var ad = document.getElementById('num');
      var el = document.getElementById('num2');
      if (el){
        el.value = '';
        ad.value= '';
      }
    }
  </script>
  <body>
  <form id="fromA" method="post" action="Admin.jsp">
   用户名:<input type="text" name="admin" id="num"><br>
   密码:<input type="password" name="pswd" id="num2"><br>
  <input type="submit" value="登录">
  <input type="button" value="取消" onclick="x()">
  </form>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值