Java 在doGet方法中创建两个cake对象并将对象保存在list中,然后请求跳转到ListServlet中,请给出代码示例继续给出上一个问题中ListServlet代码示例
时间: 2024-05-03 11:20:36 浏览: 159
好的,这是Java代码示例:
```java
public class Cake {
private int id;
private String name;
public Cake(int id, String name) {
this.id = id;
this.name = name;
}
// getter and setter methods
// ...
}
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Cake> cakes = new ArrayList<Cake>();
cakes.add(new Cake(1, "Chocolate Cake"));
cakes.add(new Cake(2, "Cheesecake"));
request.setAttribute("cakes", cakes);
RequestDispatcher dispatcher = request.getRequestDispatcher("/list");
dispatcher.forward(request, response);
}
}
public class ListServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Cake> cakes = (List<Cake>) request.getAttribute("cakes");
// Output the cakes list
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>List of Cakes</h1>");
out.println("<ul>");
for (Cake cake : cakes) {
out.println("<li>" + cake.getName() + "</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}
```
请注意,这个代码示例仅供参考,可能需要根据您的具体需求进行修改。另外,请确保在使用Java Servlet时遵循安全最佳实践,例如验证用户输入和配置适当的安全性选项。
阅读全文