<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="doRegister.jsp" method="post">
用户名: <input type="text" name="username" required><br>
密码: <input type="password" name="password" required><br>
性别: <select name="gender">
<option value="男">男</option>
<option value="女">女</option>
</select><br>
<input type="submit" value="注册">
</form>
</body>
</html>
<%@page import="java.nio.file.Files"%>
<%@page import="java.nio.file.Paths"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.BufferedWriter"%>
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String userData = username + "," + password + "," + gender;
String filePath = getServletContext().getRealPath("/") + "user.txt";
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
List<String> lines = Files.readAllLines(Paths.get(filePath));
boolean userExists = lines.stream().anyMatch(line -> line.startsWith(username + ","));
if (userExists) {
out.println("用户已存在,请尝试其他用户名。");
} else {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
writer.write(userData);
writer.newLine();
}
out.println("注册成功!");
}
%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="doLogin.jsp" method="post">
用户名: <input type="text" name="username" required><br>
密码: <input type="password" name="password" required><br>
<input type="submit" value="登录">
</form>
</body>
</html>
<%@page import="java.nio.file.Files"%>
<%@page import="java.nio.file.Paths"%>
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String filePath = getServletContext().getRealPath("/") + "user.txt";
List<String> lines = Files.readAllLines(Paths.get(filePath));
boolean userFound = false;
boolean passwordCorrect = false;
for (String line : lines) {
String[] userData = line.split(",");
if (userData[0].equals(username)) {
userFound = true;
if (userData[1].equals(password)) {
passwordCorrect = true;
break;
}
}
}
if (!userFound) {
out.println("用户名不存在。");
} else if (!passwordCorrect) {
out.println("密码错误,请重试。");
} else {
out.println("登录成功!欢迎 " + username + "!");
}
%>