MVC Lecture
MVC Lecture
History of MVC
Features of MVC
MVC Architecture Diagram
View
● A View is that part of the application that represents the presentation
of data.
● Views are created by the data collected from the model data. A view
requests the model to give information so that it resents the output
presentation to the user.
● The view also represents the data from chats, diagrams, and tables.
For example, any customer view will include all the UI components
like text boxes, drop downs, etc.
Controller
● The Controller is that part of the application that handles the user
interaction.
● The controller interprets the mouse and keyboard inputs from the
user, informing the model and the view to change as appropriate.
● A Controller send's commands to the model to update its state(E.g.,
Saving a specific document).
● The controller also sends commands to its associated view to change
the view's presentation (For example scrolling a particular
document).
Model
● The model component stores data and its related logic. It represents
data that is being transferred between controller components or any
other related business logic.
● For example, a Controller object will retrieve the customer info from
the database. It manipulates data and sends it back to the database
or uses it to render the same data.
● It responds to the request from the views and also responds to
instructions from the controller to update itself.
● It is also the lowest level of the pattern which is responsible for
maintaining data.
MVC Examples
Example 1:
● Let's assume you go to a restaurant. You will not go to the kitchen
and prepare food which you can surely do at your home. Instead,
you just go there and wait for the waiter to come on.
● Now the waiter comes to you, and you just order the food. The
waiter doesn't know who you are and what you want. He just wrote
down the details of your food order.
● Then, the waiter moves to the kitchen. In the kitchen, the waiter does
not prepare your food.
● The cook prepares your food. The waiter is given your order to him
along with your table number.
● Cook then prepared food for you. He uses ingredients to cook the
food. Let's assume that you order a vegetable sandwich. Then he
needs bread, tomato, potato, capsicum, onion, bit, cheese, etc.
which he sources from the refrigerator
● Cook the final hand over the food to the waiter. Now it is the job of
the waiter to move this food outside the kitchen.
● Now the waiter knows which food you have ordered and how they
are served.
In this case,
View= You
Waiter= Controller
Cook= Model
Refrigerator= Data
Example 2:
● Car runs from the engine take fuel from storage, but it runs only
using mentioned user interface devices.
Model Layer:
View Layer:
Controller Layer:
● Ruby on Rails
● Django
● CakePHP
● Yii
● CherryPy
● Spring MVC
● Catalyst
● Rails
● Zend Framework
● CodeIgniter
● Laravel
● Fuel PHP
● Symphony
Disadvantages of using MVC
Summary
● The MVC is an architectural pattern that separates an application
into 1) Model, 2) View and 3) Controller
● Model: It includes all the data and its related logic
● View: Present data to the user or handles user interaction
● Controller: An interface between Model and View components
● MVC architecture first discussed in 1979 by Trygve Reenskaug
● MVC is a highly testable, extensible and pluggable framework
● Some popular MVC frameworks are Rails, Zend Framework,
CodeIgniter, Laravel, Fuel PHP, etc.
File: index.jsp (a
page that gets input from the user)
5. </form>
File: ControllerServlet ( a servlet that acts as a controller)
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class ControllerServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse
response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. String name=request.getParameter("name");
15. String password=request.getParameter("password");
16. LoginBean bean=new LoginBean();
17. bean.setName(name);
18. bean.setPassword(password);
19. request.setAttribute("bean",bean);
20. boolean status=bean.validate();
21. if(status){
22. RequestDispatcher
rd=request.getRequestDispatcher("login-success.jsp");
23. rd.forward(request, response);
24. }
25. else{
26. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
27. rd.forward(request, response);
28. }
29. }
30. @Override
31. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
32. throws ServletException, IOException {
33. doPost(req, resp);
34. }
35.}
File: LoginBean.java (files act as view components)
1. package com.javatpoint;
2. public class LoginBean {
3. private String name,password;
4.
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10.}
11.public String getPassword() {
12. return password;
13.}
14.public void setPassword(String password) {
15. this.password = password;
16.}
17.public boolean validate(){
18. if(password.equals("admin")){
19. return true;
20. }
21. else{
22. return false;
23. }
24.}
25.}
File: login-success.jsp
1. <%@page import="com.javatpoint.LoginBean"%>
2.
4. <%
5. LoginBean bean=(LoginBean)request.getAttribute("bean");
6. out.print("Welcome, "+bean.getName());
7. %>
File: login-error.jsp (f iles act as view components)
Model Layer
Employee
package net.javaguides.mvc.model;
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
EmployeeService
package net.javaguides.mvc.service;
import java.util.Arrays;
import java.util.List;
import net.javaguides.mvc.model.Employee;
public class EmployeeService {
public List < Employee > getEmployees() {
return Arrays.asList(new Employee(1, "Ramesh", "Fadatare"), new
Employee(2, "Tony", "Stark"),
new Employee(3, "Tom", "Cruise"));
}
}
Controller Layer
class EmployeeServlet:
package net.javaguides.mvc.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 net.javaguides.mvc.service.EmployeeService;
@WebServlet(name = "EmployeeServlet", urlPatterns = "/employees")
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
private EmployeeService employeeService = null;
public void init() {
employeeService = new EmployeeService();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("employees", employeeService.getEmployees());
RequestDispatcher dispatcher =
request.getRequestDispatcher("/WEB-INF/jsp/employees.jsp");
dispatcher.forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
View Layer
<%@page import="java.util.List"%>
<%@page import="net.javaguides.mvc.model.Employee"%>
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Student Record</title>
</head>
<body>
<% List<Employee> employees =
(List<Employee>)request.getAttribute("employees"); %>
<table border="1" style="width: 50%" height="50%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<!-- for (Todo todo: todos) { -->
<% for(Employee employee : employees){ %>
<tr>
<td><%=employee.getId()%></td>
<td><%=employee.getFirstName()%></td>
<td><%=employee.getLastName()%></td>
</tr>
<%} %>
</tbody>
</table>
</body>
</html>