编写一个JSP程序,实现通过EL获取并显示用户注册信息的功能,要求包括用户名、密码、性别(采用单选按钮)、爱好(采用复选框)等信息。
时间: 2024-05-15 15:15:16 浏览: 117
以下是一个简单的实现:
1. 创建一个register.jsp文件,包含以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="register.do" method="post">
<label>用户名:</label>
<input type="text" name="username"><br><br>
<label>密码:</label>
<input type="password" name="password"><br><br>
<label>性别:</label>
<input type="radio" name="gender" value="男">男
<input type="radio" name="gender" value="女">女<br><br>
<label>爱好:</label>
<input type="checkbox" name="hobby" value="游泳">游泳
<input type="checkbox" name="hobby" value="跑步">跑步
<input type="checkbox" name="hobby" value="看电影">看电影<br><br>
<input type="submit" value="注册">
</form>
</body>
</html>
```
2. 创建一个RegisterServlet类,实现用户注册功能,并将注册信息存储到一个User对象中。以下是一个简单的实现:
```java
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String[] hobbies = request.getParameterValues("hobby");
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setGender(gender);
user.setHobbies(Arrays.asList(hobbies));
request.setAttribute("user", user);
request.getRequestDispatcher("registerResult.jsp").forward(request, response);
}
}
```
3. 创建一个registerResult.jsp文件,用于显示用户注册信息。使用EL表达式获取User对象的属性值,并将其显示在页面上。以下是一个简单的实现:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册结果</title>
</head>
<body>
<h1>注册结果</h1>
<p>用户名:${user.username}</p>
<p>密码:${user.password}</p>
<p>性别:${user.gender}</p>
<p>爱好:${user.hobbies}</p>
</body>
</html>
```
注意:在以上代码中,User类需要自行定义,包含以下属性和方法:
```java
public class User {
private String username;
private String password;
private String gender;
private List<String> hobbies;
// getters and setters
}
```
阅读全文