What is MVC Framework?
● The Model-View-Controller (MVC) framework is an architectural
pattern that separates an application into three main logical
components Model, View, and Controller.
● Each architecture component is built to handle specific development
aspects of an application.
● MVC separates the business logic and presentation layer from each
other. It was traditionally used for desktop graphical user interfaces
(GUIs). MVC architecture has become popular for designing web
applications as well as mobile apps.
History of MVC
● MVC architecture first discussed in 1979 by Trygve Reenskaug
● MVC model was first introduced in 1987 in the Smalltalk
programming language.
● MVC was first time accepted as a general concept, in a 1988 article
● In the recent time, MVC pattern is widely used in modern web
applications
Features of MVC
● Easy and frictionless testability. Highly testable, extensible and
pluggable framework
● Offers full control over your HTML as well as your URLs
● Leverage existing features provided by ASP.NET, JSP, Django, etc.
● Clear separation of logic: Model, View, Controller. Separation of
application tasks viz. business logic, Ul logic, and input logic
● URL Routing for SEO Friendly URLs. Powerful URL- mapping for
comprehensible and searchable URLs
● Supports for Test Driven Development (TDD)
MVC Architecture
MVC Architecture Diagram
Three important MVC the components are:
● 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
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
Let's see Model View Controller from daily life:
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 driving mechanism is another example of the MVC model.
● Every car consists of three main parts.
● View= User interface : ( Gear lever, panels, steering wheel, brake,
etc.)
● Controller- Mechanism ( Engine)
● Model- Storage ( Petrol or Diesel tank)
● Car runs from the engine take fuel from storage, but it runs only
using mentioned user interface devices.
Model Layer:
● Model Layer is the data layer.
● It consists of all the data of our web application.
● It represents a state of an application.
● The Model Layer is responsible to connect with the database as well as stores
the data into a database.
● It consists of all the classes in our application which have the connection to
the database
View Layer:
● It represents the presentation layer
● It normally represents the User Interface (UI) of the application.
● We can use HTML,CSS,JS etc to create presentation layer.
Controller Layer:
● It is an interface between the view layer and the model layer.
● It receives the request from View Layer.
● It read the data which is coming from the presentation layer.
● To read data from the presentation layer, we can use Servlet, JSP, Filter, etc.
Popular MVC web frameworks
● Ruby on Rails
● Django
● CakePHP
● Yii
● CherryPy
● Spring MVC
● Catalyst
● Rails
● Zend Framework
● CodeIgniter
● Laravel
● Fuel PHP
● Symphony
Advantages of MVC: Key Benefits
● Easy code maintenance easy to extend and grow
● MVC Model component can be tested separately from the user
● Easier support for new type of clients
● Development of the various components can be performed
parallelly.
● It helps you to avoid complexity by dividing an application into the
three units. Model, view, and controller
● It only uses a Front Controller pattern which process web application
requests through a single controller.
● Offers the best support for test-driven development
● It works well for Web apps which are supported by large teams of
web designers and developers.
● Provides clean separation of concerns(SoC).
● Search Engine Optimization (SEO) Friendly.
● All classes and objects are independent of each other so that you
can test them separately.
● MVC allows logical grouping of related actions on a controller
together.
Disadvantages of using MVC
● Difficult to read, change, to unit test, and reuse this model
● The framework navigation can sometimes be time complex as it
introduces new layers of abstraction which requires users to adapt to
the decomposition criteria of MVC.
● No formal validation support
● Increased complexity and Inefficiency of data
● The difficulty of using MVC with the modern user interface
● There is a need for multiple programmers to conduct parallel
programming.
● Knowledge of multiple technologies is required.
● Maintenance of lots of codes in Controller
3-tier Architecture vs. MVC Architecture
Parameter 3-Tier Architecture MVC Architecture
Communication This type of architecture pattern All layers
never communicates directly with communicate
the data layer. directly using
triangle topology.
Usage 3-tier: widely used in web Generally used on
applications where the client, data applications that run
tiers, and middleware run on on a single graphical
physically separate platforms. workstation.
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.
MVC Example in JSP
In this example, we are using servlet as a controller, jsp as a view component, Java
Bean class as a model.
In this example, we have created 5 pages:
● index.jsp a page that gets input from the user.
● ControllerServlet.java a servlet that acts as a controller.
● login-success.jsp and login-error.jsp files act as view components.
● web.xml file for mapping the servlet.
File: index.jsp (a
page that gets input from the user)
1. <form action="ControllerServlet" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
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.
3. <p>You are successfully logged in!</p>
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)
1. <p>Sorry! username or password error</p>
2. <%@ include file="index.jsp" %>
File: web.xml (file for mapping the servlet)
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns=" http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5. id="WebApp_ID" version="3.0">
6.
7. <servlet>
8. <servlet-name>s1</servlet-name>
9. <servlet-class>com.javatpoint.ControllerServlet</servlet-class>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>s1</servlet-name>
13. <url-pattern>/ControllerServlet</url-pattern>
14. </servlet-mapping>
15.</web-app>
Output
MVC Example in JSP
● To implement a web application based on MVC design pattern, we’ll
create the Employee and EmployeeService classes which will act as
our Model layer.
● EmployeeServlet class will act as a Controller, and for the
presentation layer, we’ll create employees.jsp page.
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
Presentation layer employees.jsp:
<%@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>