背景介绍
本项目旨在搭建一个小型网页应用,用户输入姓名和年龄后,系统会根据年龄生成生日祝福语,并将数据保存至本地文件。通过HTML、CSS和JavaScript技术实现,确保数据可读性、交互性及日志记录功能。
思路分析
- 用户交互:前端通过输入框获取用户数据,结合按钮触发逻辑
- 数据存储:使用本地文件保存数据,确保数据持久性
- 日志记录:在后台记录请求时间和祝福语生成时间,便于调试与追踪
代码实现
HTML代码(前端结构)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>生日祝福生成器</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h2 {
text-align: center;
}
#result {
margin-bottom: 20px;
}
input, button {
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<h2>输入姓名和年龄</h2>
<input type="text" id="name" placeholder="请输入姓名" required>
<input type="number" id="age" placeholder="请输入年龄" min="1">
<button onclick="generateBirthday()">生成祝福语</button>
<div id="result">
<h3>祝福语生成结果</h3>
<p id="birthdayMessage"></p>
<p id="logTime">请求时间: <span id="logTimeDisplay">2023-10-25 15:30:00</span></p>
</div>
<script>
function generateBirthday() {
const nameInput = document.getElementById('name');
const ageInput = document.getElementById('age');
const name = nameInput.value.trim();
const age = parseInt(ageInput.value);
const message = `25岁,你的生日快乐!`;
const logTime = new Date().toLocaleTimeString(); // 记录时间戳
document.getElementById('result').innerHTML = `
祝福语: ${message}
请求时间: ${logTime}
`;
saveData(name, age);
}
function saveData(name, age) {
const filePath = 'birthday.txt';
const content = `${name},${age}`;
const file = new File([content], filePath, { type: 'text/plain' });
const reader = new FileReader();
reader.onload = function(event) {
const data = event.target.result;
const result = data.split('\n').map(line => line.trim()).join('\n');
const message = result.split('\n')[0];
document.getElementById('logTimeDisplay').textContent = logTime;
};
reader.readAsText(file);
}
</script>
</body>
</html>
Java代码(本地文件保存)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
public class BirthdayApp {
private static final String FILE_NAME = "birthday.txt";
public void saveData(String name, int age) {
try {
File file = new File(FILE_NAME);
FileOutputStream fos = new FileOutputStream(file);
fos.writeBytes(name + "," + age + "\n");
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String name = "张三";
int age = 25;
saveData(name, age);
}
}
总结
本项目通过HTML+CSS实现用户交互,使用Java编写本地文件保存逻辑,确保数据持久性和可读性。代码完整示例展示了如何保存数据、生成祝福语并记录日志,符合中级技术实现要求。