创建jsp程序实现用户登录和注册,注册要求有姓名,年龄,邮箱,并保存已经注册过的邮箱,在第二次使用相同邮箱二次注册时显示“该邮箱已注册”,注册成功后跳转到登陆界面
时间: 2024-01-09 12:05:50 浏览: 33
以下是一个简单的实现用户登录和注册的JSP程序:
index.jsp
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录和注册</title>
</head>
<body>
<h1>用户登录和注册</h1>
<% if (request.getParameter("error") != null) { %>
<p style="color:red;"><%= request.getParameter("error") %></p>
<% } %>
<form action="login.jsp" method="post">
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
<br>
<form action="register.jsp" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">年龄:</label>
<input type="number" id="age" name="age" required><br><br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required><br><br>
<% if (request.getAttribute("emailExists") != null) { %>
<p style="color:red;">该邮箱已注册</p>
<% } %>
<input type="submit" value="注册">
</form>
</body>
</html>
```
login.jsp
```html
<%
String email = request.getParameter("email");
String password = request.getParameter("password");
if (email == null || password == null) {
response.sendRedirect("index.jsp?error=请输入邮箱和密码");
}
else if (email.equals("admin@example.com") && password.equals("admin")) {
session.setAttribute("email", email);
response.sendRedirect("welcome.jsp");
}
else {
response.sendRedirect("index.jsp?error=邮箱或密码错误");
}
%>
```
register.jsp
```html
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String email = request.getParameter("email");
List<String> emails = (List<String>)application.getAttribute("emails");
if (emails == null) {
emails = new ArrayList<String>();
application.setAttribute("emails", emails);
}
if (emails.contains(email)) {
request.setAttribute("emailExists", true);
}
else {
emails.add(email);
response.sendRedirect("index.jsp");
}
%>
```
welcome.jsp
```html
<%
String email = (String)session.getAttribute("email");
if (email == null) {
response.sendRedirect("index.jsp?error=请先登录");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎</title>
</head>
<body>
<h1>欢迎,<%= email %></h1>
<a href="logout.jsp">退出登录</a>
</body>
</html>
```
logout.jsp
```html
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
```
在这个程序中,用户可以在首页进行登录和注册。当用户提交登录表单时,login.jsp会验证邮箱和密码是否正确,正确时将邮箱保存到会话中,并跳转到欢迎页面。如果验证失败,则会重定向回首页,并在URL参数中包含错误消息。当用户提交注册表单时,register.jsp会检查邮箱是否已经被注册过,如果是,则在请求中设置一个属性,以便在首页上显示错误消息。如果邮箱未被注册过,则将其添加到应用程序级别的列表中,并重定向回首页。欢迎页面和登出页面只是简单的页面,前者需要检查会话中是否存在已登录的邮箱,后者只是简单地使会话无效,并重定向回首页。