我們做Web部分程序的時(shí)候常常在網(wǎng)頁和后臺(tái)邏輯之間傳遞參數(shù),并且要引用我們的實(shí)體類,我們就要用到MVC模式編程。
    Model是模型,也就是我們的實(shí)體類;View是視圖,也就是JSP網(wǎng)頁;Control是控制,也就是Servlet后臺(tái)邏輯。
    我們要將他們區(qū)分開來,每一個(gè)部分要做自己的本職功能,不能混亂。
    下面是一個(gè)簡(jiǎn)單的小程序例子,體會(huì)一下MVC模式的思想。
   
    首先是實(shí)體類:
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;
    }

}

    后臺(tái)邏輯:
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);
    }

}

    網(wǎng)頁輸出:
<%@ 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>

    看一下運(yùn)行結(jié)果: