MVC架构的学习
1:结构介绍
2:代码实现
2.1:M
package bean; /** * @author :dazhu * @date :Created in 2020/4/30 16:25 * @description:数据库boys表的记录对象 * @modified By: * @version: $ */ public class Boy { public int id; public String name; public int userCP; public Boy(){ } public Boy(int id,String name,int userCP){ this.id = id; this.name = name; this.userCP = userCP; } 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 int getUserCP() { return userCP; } public void setUserCP(int userCP) { this.userCP = userCP; } }
注意在这里要对字段实现setter和getter方法,因为在jsp中,要默认通过这两个方法来获取模型字段。
2.2:V
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <table align='center' border='10' cellspacing='10'> <tr> <td>id</td> <td>name</td> <td>userCP</td> </tr> <c:forEach items="${boys}" var="boy" varStatus="st"> <tr> <td>${boy.id}</td> <td>${boy.name}</td> <td>${boy.userCP}</td> </tr> </c:forEach> </table>
在servlet中将结果集合放进来,进行处理和展示。
2.3:C
package MVC; import bean.Boy; import dao.BoyDAO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @author :dazhu * @date :Created in 2020/5/4 8:36 * @description: * @modified By: * @version: $ */ public class boyListServlet extends HttpServlet{ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Boy> boys = new BoyDAO().list(); request.setAttribute("boys", boys); request.getRequestDispatcher("boyList.jsp").forward(request, response); } }
通过访问servlet来进行后端数据侧处理。