案例需求:使用MVC模式編寫一個程序,當發起一個deptList.do請求時,在servlet中準備一個部門列表對象,把這個列表對象放入request做用域中轉發到deptlist.jsp,使用JSTL+EL的語法來顯示這個部門列表。部門類型是XdlDept成員變量有int id、String name、String loc。css
案例實現:html
● XdlDept類:java
package com.xdl.bean;jsp
import java.io.Serializable;ide
public class XdlDept implements Serializable{ui
private static final long serialVersionUID = 1L;this
private int deptno;spa
private String dname;htm
private String loc;對象
@Override
public String toString() {
return "XdlDept [deptno=" + deptno + ", dname=" + dname
+ ", loc=" + loc + "]\n";
}
public XdlDept(int deptno, String dname, String loc) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public XdlDept() {
super();
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
● XdlDeptController類:
package com.xdl.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xdl.bean.XdlDept;
import com.xdl.dao.XdlDeptDAO;
import com.xdl.dao.impl.XdlDeptDAOOracleImp;
@WebServlet("/deptList.do")
public class XdlDeptController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
XdlDeptDAO dao = new XdlDeptDAOOracleImp();
// 經過M層獲取數據
List<XdlDept> depts = dao.getDeptList();
//放入對應的域對象
request.setAttribute("depts", depts);
// 跳轉對應的頁面
request.getRequestDispatcher("deptlist2.jsp").
forward(request, response);
}
}
● deptList.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<style type="text/css">
table {
width:600px;
text-align: center;
border-collapse: collapse;
}
table,tr,td{
border:1px solid red;
}
</style>
</head>
<body>
<table>
<tr> <td>DEPTNO</td> <td> DNAME</td> <td> LOC</td> </tr>
<c:forEach items="${depts}" var="dept" >
<tr> <td>${dept.deptno }</td> <td> ${dept.dname }</td>
<td> ${dept.loc }</td> </tr>
</c:forEach>
</table>
</body>
</html>