ShowServlet.java:
package cn.hncu.elWeb.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.elWeb.domain.Car; import cn.hncu.elWeb.domain.Person; public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Person p = new Person(); p.setId("P001"); p.setName("Jack"); p.setAge(24); p.setPwd("123456"); Car cars[] = new Car[3]; for(int i=0;i<3;i++){ Car c = new Car(); c.setName("Car"+i); c.setNo("No."+i); c.setColor("RED"); cars[i]=c; } p.setCars(cars); request.setAttribute("p", p); request.getRequestDispatcher("/jsps/show.jsp").forward(request, response); } }
show.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h2>用户信息展示</h2> 工号:${p.id}<br/> 姓名:${p.name}<br/> 年龄:${p.age}<br/> <hr/> <h3>车辆信息</h3> <table border="1"> <tr><th>车牌号</th> <th>车名</th> <th>颜色</th></tr> <tr><td>${p.cars[0].no}</td> <td>${p.cars[0].name}</td> <td>${p.cars[0].color}</td></tr> <tr><td>${p.cars[1].no}</td> <td>${p.cars[1].name}</td> <td>${p.cars[1].color}</td></tr> <tr><td>${p.cars[2].no}</td> <td>${p.cars[2].name}</td> <td>${p.cars[2].color}</td></tr> <!-- 其实这里用这种方式很不好的-变量个数全部写死了,我们可以用JSTL把这里写活,不过我们在这里不是演示那个技术的,为了简便突出EL重点,就这样写了 --> </table> </body> </html>
演示结果: