只用jsp代码 实现管理员和用户登录,不要servlet
时间: 2024-03-19 14:44:35 浏览: 13
好的,以下是一个只使用JSP代码实现管理员和用户登录的示例:
1. 登录页面(login.jsp)
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="login.jsp" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<button type="submit">登录</button>
</form>
<%-- 检查登录结果并提示错误信息 --%>
<%
String error = request.getParameter("error");
if (error != null) {
out.println("<p style=\"color:red;\">登录失败,请检查用户名和密码!</p>");
}
%>
</body>
</html>
```
2. 管理员页面(admin.jsp)
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>管理员页面</title>
</head>
<body>
<h1>欢迎管理员 <%= session.getAttribute("username") %> 登录!</h1>
<p>这里是管理员页面。</p>
<%-- 注销按钮 --%>
<form action="login.jsp" method="post">
<input type="hidden" name="action" value="logout">
<button type="submit">注销</button>
</form>
</body>
</html>
```
3. 普通用户页面(user.jsp)
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户页面</title>
</head>
<body>
<h1>欢迎用户 <%= session.getAttribute("username") %> 登录!</h1>
<p>这里是用户页面。</p>
<%-- 注销按钮 --%>
<form action="login.jsp" method="post">
<input type="hidden" name="action" value="logout">
<button type="submit">注销</button>
</form>
</body>
</html>
```
4. 登录处理逻辑(login.jsp)
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String action = request.getParameter("action");
// 检查用户名和密码是否正确
if ("admin".equals(username) && "admin123".equals(password)) {
// 将用户信息存储在Session中,以便后续操作中进行验证
session.setAttribute("username", username);
// 根据用户类型,跳转到不同的页面
if ("admin".equals(username)) {
response.sendRedirect("admin.jsp");
} else {
response.sendRedirect("user.jsp");
}
} else if ("logout".equals(action)) {
// 用户注销,从Session中删除用户信息
session.removeAttribute("username");
// 重定向到登录页面
response.sendRedirect("login.jsp");
} else {
// 登录失败,返回到登录页面并提示错误信息
response.sendRedirect("login.jsp?error=true");
}
%>
```
以上代码仅供参考,可能存在安全风险和性能问题,请谨慎使用。建议使用Servlet或其他框架实现更为安全和高效的登录功能。