编写用户实体类UserName.java,用户填写表单信息formin.jsp,提交给inputServlet,在Servlet中使用JavaBean存储表单信息,并且将表单信息展示在formout.jsp,再利用EL表达式获取JavaBean的属性并展示。
时间: 2025-01-05 15:44:10 浏览: 11
首先,我们需要创建一个名为`UserName.java`的用户实体类,它通常是一个简单的Java类,包含用户的姓名属性和其他可能需要的数据字段:
```java
// UserName.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class UserName {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// getters and setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// constructor and toString method for better representation
public UserName(String name) {
this.name = name;
}
}
```
接下来,用户会在`formin.jsp`表单页面上输入他们的信息:
```jsp
<!-- formin.jsp -->
<form action="inputServlet" method="post">
<label for="name">用户名:</label>
<input type="text" id="name" name="username" value="" required><br>
<!-- other form fields... -->
<input type="submit" value="提交">
</form>
```
当用户点击提交按钮时,表单数据会被发送到`inputServlet`。在这个Servlet中,我们将使用JavaBean(这里我们假设已经导入了UserModel包下的UserName类)来处理并存储这些信息:
```java
// inputServlet.java (部分代码)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/inputServlet")
public class InputServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
User user = new UserName(username);
// Assuming you have a UserService or similar to store the user object
userService.saveUser(user);
request.getRequestDispatcher("formout.jsp").forward(request, response);
}
}
```
然后,`formout.jsp`会显示保存的表单信息,并通过EL表达式获取JavaBean的属性:
```jsp
<!-- formout.jsp -->
<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<body>
<%@ include file="header.jsp" %>
<h2>User Information:</h2>
<p>用户名: ${user.name}</p>
<!-- display any additional attributes as needed -->
<p>Email: ${user.email} (假设email也是一个属性)</p>
</body>
</html>
```
阅读全文