编写Computer实体类 1.3 编写AddComputerServlet类,实现新增功能。将笔记本对象存入Set集合,再将Set集合存入合适的作用域。
时间: 2023-06-24 16:05:49 浏览: 87
以下是Computer实体类的代码:
```java
public class Computer {
private String brand;
private String model;
private double price;
public Computer(String brand, String model, double price) {
this.brand = brand;
this.model = model;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
```
以下是AddComputerServlet类的代码:
```java
@WebServlet("/addComputer")
public class AddComputerServlet extends HttpServlet {
private Set<Computer> computerSet;
@Override
public void init() {
computerSet = new HashSet<>();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String brand = request.getParameter("brand");
String model = request.getParameter("model");
double price = Double.parseDouble(request.getParameter("price"));
Computer computer = new Computer(brand, model, price);
computerSet.add(computer);
ServletContext context = request.getServletContext();
context.setAttribute("computerSet", computerSet);
response.sendRedirect(request.getContextPath() + "/showComputer.jsp");
}
}
```
在该Servlet中,我们首先在init()方法中初始化了一个空的HashSet用于存储Computer对象。在doPost()方法中,我们获取了用户输入的品牌、型号和价格,创建了一个新的Computer对象并将其添加到HashSet中。然后,我们使用ServletContext将HashSet对象存储在应用程序范围内。最后,我们将用户重定向到展示电脑信息的JSP页面。
阅读全文