以下是一个简单的 JSP 小程序,使用 session 模拟用户登录:

index.jsp

<!DOCTYPE html>
<html>
<head>
    <title>登录页面</title>
</head>
<body>
    <h2>登录页面</h2>
    <form action='login.jsp' method='post'>
        <label for='username'>用户名:</label>
        <input type='text' id='username' name='username' required><br><br>
        <label for='password'>密码:</label>
        <input type='password' id='password' name='password' required><br><br>
        <input type='submit' value='登录'>
    </form>
</body>
</html>

login.jsp

<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8' %>
<% 
    String username = request.getParameter('username');
    String password = request.getParameter('password');

    if (username != null && password != null && username.equals('admin') && password.equals('123456')) {
        session.setAttribute('username', username);
        response.sendRedirect('welcome.jsp');
    } else {
        response.sendRedirect('index.jsp');
    }
%>

welcome.jsp

<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8' %>
<% 
    String username = (String) session.getAttribute('username');
%>
<!DOCTYPE html>
<html>
<head>
    <title>欢迎页面</title>
</head>
<body>
    <h2>欢迎页面</h2>
    <% if (username != null) { %>
        <p>欢迎 ' + username + ' 登录!</p>
    <% } else { %>
        <p>请先登录!</p>
    <% } %>
    <a href='logout.jsp'>退出登录</a>
</body>
</html>

logout.jsp

<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8' %>
<% 
    session.removeAttribute('username');
    response.sendRedirect('index.jsp');
%>

在这个程序中,用户在 index.jsp 页面输入用户名和密码后,点击登录按钮会提交表单到 login.jsp 页面。在 login.jsp 页面中,通过 request.getParameter 方法获取表单中的用户名和密码,如果用户名和密码正确,将用户名存储在 session 中,并重定向到 welcome.jsp 页面;如果用户名和密码不正确,重定向到 index.jsp 页面。

在 welcome.jsp 页面中,根据 session 中是否存在用户名来判断用户是否已登录,展示相应的欢迎信息或登录提示。同时提供退出登录的功能,点击退出登录链接会清除 session 中的用户名并重定向到 index.jsp 页面。

请确保在项目的 WEB-INF 目录下存在 web.xml 文件,并已配置好 JSP 的 servlet 映射。

JSP Session 用户登录示例 - 简单易懂