MVC模式介紹
MVC(Model-View-Controller)是一種軟件設計模式,最早出現在Smalltalk語言中,后來在Java中得到廣泛應用,并被Sun公司推薦為Java EE平臺的設計模式。它把應用程序分成了三個核心模塊:模型層、視圖層和控制層。
數據模型層
表示數據封裝功能,負責處理業務邏輯和數據存儲。例如,在一個Web應用中,模型層可能包含數據庫訪問類,用來讀寫數據庫中的數據。一個或多個JavaBean對象,用于存儲數據,JavaBean主要提供簡單的setXXX()方法和getXXX()方法,在這些方法中不涉及對數據的具體處理細節
public class EmployeeDAO {public List<Employee> getAllEmployees() { ... }public void addEmployee(Employee employee) { ... }public void updateEmployee(Employee employee) { ... }public void deleteEmployee(int id) { ... }
}
?視圖層
表示數據顯示功能,負責顯示數據給用戶看。例如,在一個Web應用中,視圖層可能是HTML頁面或者JSP文件,用來展示數據。一個或多個JSP頁面,為模型提供數據顯示,JSP頁面主要使用 HTML標記和JavaBean標記來顯示數據。
<html>
<body><table><tr><th>ID</th><th>Name</th><th>Salary</th></tr><% for (Employee e : employees) { %><tr><td><%= e.getId() %></td><td><%= e.getName() %></td><td><%= e.getSalary() %></td></tr><% } %></table>
</body>
</html>
?控制器層
表示流程控制功能,負責接收用戶的請求,調用模型層的方法,然后決定如何顯示數據。例如,在一個Web應用中,控制器可能是Servlet或者Action類,用來處理HTTP請求。一個或多個Servlet對象,根據視圖提交的要求進行數據處理操作,并將有關的結果存儲到JavaBean中,然后Servlet使用重定向或請求轉發方式請求視圖中的某個JSP頁面更新顯示?JSP中實現MVC模式
以用戶注冊模塊來介紹在JSP中如何實現MVC模式
程序結構
bean.User:模型層,實現用戶注冊的業務模型及數據庫操作;
public class User {private String username;private String password;public String getUsername() { return this.username; }public void setUsername(String username) { this.username = username; }public String getPassword() { return this.password; }public void setPassword(String password) { this.password = password; }public boolean register() {// 這里省略了數據庫操作return true;}
}
servlet.UserServlet:控制器層的角色,用于流程控制,調度模型和選擇視圖展示運行結果;
public class UserServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username = request.getParameter("username");String password = request.getParameter("password");User user = new User();user.setUsername(username);user.setPassword(password);if (user.register()) {request.setAttribute("result", "注冊成功");} else {request.setAttribute("result", "注冊失敗");}RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");dispatcher.forward(request, response);}
}
regist.jsp和result.jsp等頁面為視圖層,負責交互與結果展現
?
編程思想:
用戶通過JSP頁面的表單輸入注冊信息,表單提交后由Servlet獲取表單中的數據并交由JavaBean對象儲存用戶數據,然后將JavaBean對象的數據保存至數據庫中,最后再由Servlet通知相應的視圖顯示用戶注冊的結果。
<!-- 注冊頁面 -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>用戶注冊</title>
</head>
<body>
<form action="UserServlet">用戶名:<input type="text" name="username"><br>密碼:<input type="password" name="password"><br><input type="submit" value="注冊">
</form>
</body>
</html><!-- 結果頁面 -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>注冊結果</title>
</head>
<body>
<%String result = (String) request.getAttribute("result");
%>
<%= result %>
</body>
</html>