用session,application做个用户注册网页
时间: 2023-09-04 17:09:34 浏览: 51
对于一个用户注册网页,需要实现以下功能:
1. 用户可以输入用户名、密码、邮箱等信息进行注册。
2. 注册成功后,将用户信息保存在数据库中。
3. 注册失败时,给出相应的提示。
下面是使用session和application实现的用户注册网页代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form method="post" action="register.jsp">
<label>用户名:</label>
<input type="text" name="username" required><br>
<label>密码:</label>
<input type="password" name="password" required><br>
<label>确认密码:</label>
<input type="password" name="confirm_password" required><br>
<label>邮箱:</label>
<input type="email" name="email" required><br>
<input type="submit" value="注册">
</form>
</body>
</html>
```
在`register.jsp`中,首先获取用户提交的注册信息,并进行验证:
```jsp
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirm_password = request.getParameter("confirm_password");
String email = request.getParameter("email");
// 验证用户名、密码、邮箱是否为空
if (username == null || password == null || confirm_password == null || email == null) {
session.setAttribute("message", "请填写完整的注册信息!");
response.sendRedirect("index.jsp");
return;
}
// 验证密码和确认密码是否一致
if (!password.equals(confirm_password)) {
session.setAttribute("message", "密码和确认密码不一致!");
response.sendRedirect("index.jsp");
return;
}
// 验证邮箱格式是否正确
if (!email.matches("\\w+@\\w+\\.\\w+")) {
session.setAttribute("message", "邮箱格式不正确!");
response.sendRedirect("index.jsp");
return;
}
// 将用户信息保存在application中
ServletContext application = request.getServletContext();
Map<String, String> users = (Map<String, String>) application.getAttribute("users");
if (users == null) {
users = new HashMap<>();
application.setAttribute("users", users);
}
if (users.containsKey(username)) {
session.setAttribute("message", "该用户名已被注册!");
response.sendRedirect("index.jsp");
return;
} else {
users.put(username, password);
session.setAttribute("message", "注册成功!");
response.sendRedirect("index.jsp");
return;
}
%>
```
在验证通过后,将用户信息保存在application中。这样,所有用户都可以访问到这些信息,可以用于实现登录等功能。
在`index.jsp`中,显示注册结果信息:
```jsp
<%
String message = (String) session.getAttribute("message");
if (message != null) {
out.println("<p>" + message + "</p>");
session.removeAttribute("message");
}
%>
```
这样,就实现了一个简单的用户注册网页。