Model View Controller (MVC) Design Pattern in Java

The Model-View-Controller (MVC) software design pattern is a method for separating concerns within a software application. In principle, the application logic, or controller, is separated from the technology used to display information to the user, or the view layer. The model is a communications vehicle between the controller and view layers.

As the name implies, the MVC pattern has three layers: The Model defines the business layer of the application, the Controller manages the flow of the application, and the View defines the presentation layer of the application.
In this quick article, we’ll create a small web application that implements the Model View Controller (MVC) design pattern, using basic Servlets and JSPs.
Get the source code of this tutorial on my GitHub Repository.

Key features of the MVC pattern:

  1. It separates the presentation layer from the business layer
  2. The Controller performs the action of invoking the Model and sending data to View
  3. The Model is not even aware that it is used by some web application or a desktop application

Model-View-Controller (MVC)

  1. The Model Layer - This is the data layer that contains the business logic of the system, and also represents the state of the application. It’s independent of the presentation layer, the controller fetches the data from the Model layer and sends it to the View layer.
  2. The Controller Layer - The controller layer acts as an interface between View and Model. It receives requests from the View layer and processes them, including the necessary validations.
  3. The View Layer - This layer represents the output of the application, usually some form of UI. The presentation layer is used to display the Model data fetched by the Controller.

Java MVC Web Application using JSP and Servlet Example

To implement a web application based on the 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 an employees.jsp page.

Model Layer

Let's create the Employee and EmployeeService classes which will act as our 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

Now let’s create our Controller 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

Next, let’s write our 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>

Conclusion

In this tutorial, we’ve learned about the MVC i.e. Model View Controller architecture, and we focused on how to implement a simple example using JSP and Servlet.

Servlet + JSP + JDBC + MySQL Examples

Get source code of this tutorial on my GitHub Repository.

Comments