How to Implement MVC Architecture in Java?

Swatee Chand
Edureka
Published in
7 min readAug 2, 2019

--

In the Web Development field, Model-View-Controller is one of the most talked-about design patterns in the web programming world today. MVC Architecture was initially included in the two major web development frameworks — Struts and Ruby on Rails. In this article, let’s explore a little bit about MVC Architecture in Java.

The topics that will be covered in this article are as follows:

  • What is MVC Architecture in Java?
  • Advantages of MVC Architecture
  • Demo: Implementation of MVC using Java

Before we actually get into the technicalities of MVC Architecture, there are certain concepts that you need to know.

  • Design Pattern, in software engineering, is a technique to solve a commonly occurring problem when designing software.
  • Designing Model, specifies what type of architecture you use to solve the problem or design the model.
  • There are two types of design models: Model 1 Architecture, Model 2(MVC) Architecture.

What is MVC Architecture in Java?

Model designs based on MVC architecture follow the MVC design pattern and they separate the application logic from the user interface when designing software. As the name implies MVC pattern has three layers, which are:

  • Model — Represents the business layer of the application
  • View — Defines the presentation of the application
  • Controller — Manages the flow of the application

In the Java Programming context, the Model consists of simple Java classes, the View displays the data and the Controller consists of servlets. This separation results in user requests being processed as follows:

  1. The browser on the client sends a request for a page to the controller present on the server
  2. The controller performs the action of invoking the model, thereby, retrieving the data it needs in response to the request
  3. The controller then gives the retrieved data to the view
  4. The view is rendered and sent back to the client for the browser to display

Separating a software application into these three distinct components is a good idea for a number of reasons. Let’s take a look at what those are.

Advantages of MVC Architecture in Java

MVC architecture offers a lot of advantages for a programmer when developing applications, which include:

  • Multiple developers can work with the three layers (Model, View, and Controller) simultaneously
  • Offers improved scalability, that supplements the ability of the application to grow
  • As components have a low dependency on each other, they are easy to maintain
  • A model can be reused by multiple views which provides reusability of code
  • Adoption of MVC makes an application more expressive and easy to understand
  • Extending and testing of the application becomes easy

Now you know why the MVC is the most popular design patterns in the web programming world. But, if you are still struggling to get your head around the concept of MVC, don’t worry. We will dig deep into each of these layers and learn their purpose with the help of an example program.

Implementation of MVC using Java

To implement a web application based on MVC design pattern, we will create

  • Course Class, which acts as the model layer
  • CourseView Class, which defines the presentation layer (view layer)
  • CourseContoller Class, which acts as a controller

Now, let’s explore these layers one by one.

The Model Layer

In the MVC design pattern, the model is the data layer that defines the business logic of the system and also represents the state of the application. objects retrieve and store the state of the model in a database. Through this layer, we apply rules to data, which eventually represents the concepts our application manages. Now, let’s create a model using Course Class.

package MyPackage;
public class Course {
private String CourseName;
private String CourseId;
private String CourseCategory;
public String getId() {
return CourseId;
}
public void setId(String id) {
this.CourseId = id;
}
public String getName() {
return CourseName;
}
public void setName(String name) {
this.CourseName = name;
}
public String getCategory() {
return CourseCategory;
}
public void setCategory(String category) {
this.CourseCategory = category;
}
}

The code is easy to understand and is self-explanatory. It consists of functions to get/set course details.

The View Layer

This layer of the MVC design pattern represents the output of the application or the user interface. It displays the data fetched from the model layer by the controller and presents the data to the user whenever asked for. It receives all the information it needs from the controller and it doesn’t need to interact with the business layer directly. Let’s create a view using CourseView Class.

package MyPackage;public class CourseView {
public void printCourseDetails(String CourseName, String CourseId, String CourseCategory){
System.out.println("Course Details: ");
System.out.println("Name: " + CourseName);
System.out.println("Course ID: " + CourseId);
System.out.println("Course Category: " + CourseCategory);
}
}

This code is simply to print the values to the console. Next up we have the controller of the web application.

The Controller Layer

The Controller is like an interface between Model and View. It receives the user requests from the view layer and processes them, including the necessary validations. The requests are then sent to the model for data processing. Once they are processed, the data is again sent back to the controller and then displayed on the view. Let’s create CourseContoller Class which acts as a controller.

package MyPackage;public class CourseController {
private Course model;
private CourseView view;
public CourseController(Course model, CourseView view){
this.model = model;
this.view = view;
}
public void setCourseName(String name){
model.setName(name);
}
public String getCourseName(){
return model.getName();
}
public void setCourseId(String id){
model.setId(id);
}
public String getCourseId(){
return model.getId();
}
public void setCourseCategory(String category){
model.setCategory(category);
}
public String getCourseCategory(){
return model.getCategory();
}
public void updateView(){
view.printCourseDetails(model.getName(), model.getId(), model.getCategory());
}
}

A cursory glance at the code will tell us that this controller class is just responsible for calling the model to get/set the data and updating the view based on that. Now let’s have a look at how all of these are tied together.

Main Java Class

Let’s call this class “MVCPatternDemo.java”. Check out the code below.

package MyPackage;public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the database
Course model = retriveCourseFromDatabase();
//Create a view : to write course details on console
CourseView view = new CourseView();
CourseController controller = new CourseController(model, view);
controller.updateView();
//update model data
controller.setCourseName("Python");
System.out.println("nAfter updating, Course Details are as follows");
controller.updateView();
} private static Course retriveCourseFromDatabase(){
Course course = new Course();
course.setName("Java");
course.setId("01");
course.setCategory("Programming");
return course;
}
}

The above class fetches the course data from the Further, it also invokes the function using which the user enters the set of values. It then pushes those values into the Course model. Then, it initializes the view we had created earlier in the article. CourseController class and binds it to the Course class and the CourseView class. The updateView() method which is a part of the controller then updates the course details on the console. Check out the output below.

Output

Course Details:
Name: Java
Course ID: 01
Course Category: Programming
After updating, Course Details are as follows
Course Details:
Name: Python
Course ID: 01
Course Category: Programming

The MVC Architecture provides an altogether new level of modularity to your code which makes it a lot more readable and maintainable. This brings us to the end of this article. Hope you are clear with all that has been shared with you.

This brings us to the end of our blog on Advanced Java Tutorial. I hope you found this blog informative and added value to your knowledge.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at https://www.edureka.co on August 2, 2019.

--

--