我们做Web部分程序的时候常常在网页和后台逻辑之间传递参数,并且要引用我们的实体类,我们就要用到MVC模式编程。
Model是模型,也就是我们的实体类;View是视图,也就是JSP网页;Control是控制,也就是Servlet后台逻辑。
我们要将他们区分开来,每一个部分要做自己的本职功能,不能混乱。
下面是一个简单的小程序例子,体会一下MVC模式的思想。
首先是实体类:
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
后台逻辑:
public class ELServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
List<User> list = new ArrayList<User>();
for(int i=0;i<8;i++){
User u = new User();
u.setId(i);
u.setName("name"+i);
list.add(u);
}
request.setAttribute("UserList",list);
request.getRequestDispatcher("/c_forEach.jsp").forward(request, response);
}
}
网页输出:
<%@ page language="java" import="java.util.*,com.bx.jstl.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'c_forEach.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table>
<tr><th>ID</th><th>Name</th><th>index</th><th>count</th><th>first</th><th>last</th></tr>
<c:forEach var="user" items="${UserList}" varStatus="status">
<tr>
<td>
${user.id}
</td>
<td>
${user.name}
</td>
<td>
${status.index}
</td>
<td>
${status.count}
</td>
<td>
${status.first}
</td>
<td>
${status.last}
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
看一下运行结果: