背景介绍
随着互联网的普及,用户注册与登录功能已成为现代Web应用的核心组成部分。本项目旨在为用户提供注册和登录功能,支持用户名和密码的验证,并通过本地文件存储登录状态以提高系统的可维护性。
思路分析
本项目采用HTML、CSS和JavaScript构建用户界面,通过表单验证用户名和密码,并实现本地文件存储以支持用户登录状态的持久化。核心实现包括:
- 表单验证逻辑:通过检查用户名和密码的格式,验证是否包含大小写字母、数字等基本规则。
- 本地文件存储:利用Python的json模块读写本地文件,实现用户登录状态的持久化存储。
代码实现
1. HTML/CSS表单结构
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h2 {
text-align: center;
}
.form-group {
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
padding: 8px 16px;
margin-top: 5px;
cursor: pointer;
}
#status {
margin-top: 10px;
font-size: 18px;
}
</style>
</head>
<body>
<h2>用户登录</h2>
<form onsubmit="validateLogin(event)">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">提交</button>
<div id="status" class="status">登录成功!</div>
</form>
<script>
function validateLogin(event) {
event.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
if (username.length < 3 || username.match(/^[a-zA-Z]*$/)) {
alert("用户名必须至少3个字符,且只能包含字母!");
return;
}
if (password.length < 8 || password.match(/^(?=.*[a-z])(?=.*[0-9])/.test(password))) {
alert("密码长度至少8位,且至少包含数字和字母!");
return;
}
const status = loadLoginStatus();
status ? document.getElementById('status').textContent = "登录成功!" : alert("登录失败,请重新尝试!");
}
function loadLoginStatus() {
try {
const json = JSON.parse(localStorage.getItem('loginStatus'));
return json;
} catch (error) {
return null;
}
}
</script>
</body>
</html>
2. Python脚本实现
# 本地文件读写功能示例(假设使用Python)
import json
def save_login_status(username, password):
with open('login.json', 'w') as f:
json.dump({"username": username, "password": password}, f)
print("登录成功!")
def load_login_status():
try:
with open('login.json', 'r') as f:
return json.load(f)
except FileNotFoundError:
return None
# 示例使用
save_login_status("admin", "123456")
response = load_login_status()
print(response)
总结
本项目通过HTML/CSS构建用户表单,结合JavaScript实现表单验证逻辑,并利用Python的json模块实现本地文件存储功能。核心知识点包括文件操作、JSON数据格式化以及数据验证逻辑的实现。该项目可以在1~3天内完成实现,并能够满足用户注册与登录的基本需求。
通过上述代码实现,用户可以轻松地完成注册和登录功能,确保系统的安全性和可维护性。