Java/J2EE and SOA (344 Blogs) Become a Certified Professional
Java/J2EE and SOA

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (341 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE Programming & Frameworks blog posts

How to Implement MVC Architecture in Java?

Last updated on Feb 25,2025 86.1K Views

image not found!image not found!image not found!image not found!Copy Link!
6 / 22 Blog from Advance Java

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.
Why Companies are Looking to Hire Full Stack Developers

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

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

     MVC - MVC Architecture in Java - Edureka

    In 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 which defines the business logic of the system and also represents the state of the application. The model 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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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 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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    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 function using which 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. Further, it also invokes the 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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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.

    If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

    Make sure you practice as much as possible and revert your experience.  

    Read Also Write your own MVC framework

     

    Check out the Java Course Online by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

    Got a question for us? Please mention it in the comments section of this ‘MVC Architecture in Java’ article and we will get back to you as soon as possible.

     

    Comments
    0 Comments

    Join the discussion

    Browse Categories

    webinar REGISTER FOR FREE WEBINAR
    +91
    • India (भारत)+91
    • United States+1
    • United Kingdom+44
    • Afghanistan (‫افغانستان‬‎)+93
    • Albania (Shqipëri)+355
    • Algeria (‫الجزائر‬‎)+213
    • Andorra+376
    • Angola+244
    • Argentina+54
    • Armenia (Հայաստան)+374
    • Aruba+297
    • Australia+61
    • Austria (Österreich)+43
    • Azerbaijan (Azərbaycan)+994
    • Bahamas+1242
    • Bahrain (‫البحرين‬‎)+973
    • Bangladesh (বাংলাদেশ)+880
    • Barbados+1246
    • Belarus (Беларусь)+375
    • Belgium (België)+32
    • Belize+501
    • Benin (Bénin)+229
    • Bermuda+1441
    • Bhutan (འབྲུག)+975
    • Bolivia+591
    • Bosnia and Herzegovina (Босна и Херцеговина)+387
    • Botswana+267
    • Brazil (Brasil)+55
    • British Indian Ocean Territory+246
    • British Virgin Islands+1284
    • Brunei+673
    • Bulgaria (България)+359
    • Burkina Faso+226
    • Burundi (Uburundi)+257
    • Cambodia (កម្ពុជា)+855
    • Cameroon (Cameroun)+237
    • Canada+1
    • Cape Verde (Kabu Verdi)+238
    • Caribbean Netherlands+599
    • Cayman Islands+1345
    • Central African Republic (République centrafricaine)+236
    • Chad (Tchad)+235
    • Chile+56
    • China (中国)+86
    • Christmas Island+61
    • Cocos (Keeling) Islands+61
    • Colombia+57
    • Comoros (‫جزر القمر‬‎)+269
    • Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)+243
    • Congo (Republic) (Congo-Brazzaville)+242
    • Cook Islands+682
    • Costa Rica+506
    • Côte d’Ivoire+225
    • Croatia (Hrvatska)+385
    • Cuba+53
    • Curaçao+599
    • Cyprus (Κύπρος)+357
    • Czech Republic (Česká republika)+420
    • Denmark (Danmark)+45
    • Djibouti+253
    • Dominican Republic (República Dominicana)+1
    • Ecuador+593
    • Egypt (‫مصر‬‎)+20
    • El Salvador+503
    • Equatorial Guinea (Guinea Ecuatorial)+240
    • Eritrea+291
    • Estonia (Eesti)+372
    • Ethiopia+251
    • Falkland Islands (Islas Malvinas)+500
    • Faroe Islands (Føroyar)+298
    • Fiji+679
    • Finland (Suomi)+358
    • France+33
    • French Guiana (Guyane française)+594
    • French Polynesia (Polynésie française)+689
    • Gabon+241
    • Gambia+220
    • Georgia (საქართველო)+995
    • Germany (Deutschland)+49
    • Ghana (Gaana)+233
    • Gibraltar+350
    • Greece (Ελλάδα)+30
    • Greenland (Kalaallit Nunaat)+299
    • Grenada+1473
    • Guadeloupe+590
    • Guatemala+502
    • Guernsey+44
    • Guinea (Guinée)+224
    • Guinea-Bissau (Guiné Bissau)+245
    • Guyana+592
    • Haiti+509
    • Honduras+504
    • Hong Kong (香港)+852
    • Hungary (Magyarország)+36
    • Iceland (Ísland)+354
    • India (भारत)+91
    • Indonesia+62
    • Iran (‫ایران‬‎)+98
    • Iraq (‫العراق‬‎)+964
    • Ireland+353
    • Isle of Man+44
    • Israel (‫ישראל‬‎)+972
    • Italy (Italia)+39
    • Jamaica+1876
    • Japan (日本)+81
    • Jersey+44
    • Jordan (‫الأردن‬‎)+962
    • Kazakhstan (Казахстан)+7
    • Kenya+254
    • Kiribati+686
    • Kosovo+383
    • Kuwait (‫الكويت‬‎)+965
    • Kyrgyzstan (Кыргызстан)+996
    • Laos (ລາວ)+856
    • Latvia (Latvija)+371
    • Lebanon (‫لبنان‬‎)+961
    • Lesotho+266
    • Liberia+231
    • Libya (‫ليبيا‬‎)+218
    • Liechtenstein+423
    • Lithuania (Lietuva)+370
    • Luxembourg+352
    • Macau (澳門)+853
    • Macedonia (FYROM) (Македонија)+389
    • Madagascar (Madagasikara)+261
    • Malawi+265
    • Malaysia+60
    • Maldives+960
    • Mali+223
    • Malta+356
    • Marshall Islands+692
    • Martinique+596
    • Mauritania (‫موريتانيا‬‎)+222
    • Mauritius (Moris)+230
    • Mayotte+262
    • Mexico (México)+52
    • Micronesia+691
    • Moldova (Republica Moldova)+373
    • Monaco+377
    • Mongolia (Монгол)+976
    • Montenegro (Crna Gora)+382
    • Morocco (‫المغرب‬‎)+212
    • Mozambique (Moçambique)+258
    • Myanmar (Burma) (မြန်မာ)+95
    • Namibia (Namibië)+264
    • Nauru+674
    • Nepal (नेपाल)+977
    • Netherlands (Nederland)+31
    • New Caledonia (Nouvelle-Calédonie)+687
    • New Zealand+64
    • Nicaragua+505
    • Niger (Nijar)+227
    • Nigeria+234
    • Niue+683
    • Norfolk Island+672
    • North Korea (조선 민주주의 인민 공화국)+850
    • Norway (Norge)+47
    • Oman (‫عُمان‬‎)+968
    • Pakistan (‫پاکستان‬‎)+92
    • Palau+680
    • Palestine (‫فلسطين‬‎)+970
    • Panama (Panamá)+507
    • Papua New Guinea+675
    • Paraguay+595
    • Peru (Perú)+51
    • Philippines+63
    • Poland (Polska)+48
    • Portugal+351
    • Puerto Rico+1
    • Qatar (‫قطر‬‎)+974
    • Réunion (La Réunion)+262
    • Romania (România)+40
    • Russia (Россия)+7
    • Rwanda+250
    • Saint Barthélemy+590
    • Saint Helena+290
    • Saint Martin (Saint-Martin (partie française))+590
    • Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)+508
    • Samoa+685
    • San Marino+378
    • São Tomé and Príncipe (São Tomé e Príncipe)+239
    • Saudi Arabia (‫المملكة العربية السعودية‬‎)+966
    • Senegal (Sénégal)+221
    • Serbia (Србија)+381
    • Seychelles+248
    • Sierra Leone+232
    • Singapore+65
    • Sint Maarten+1721
    • Slovakia (Slovensko)+421
    • Slovenia (Slovenija)+386
    • Solomon Islands+677
    • Somalia (Soomaaliya)+252
    • South Africa+27
    • South Korea (대한민국)+82
    • South Sudan (‫جنوب السودان‬‎)+211
    • Spain (España)+34
    • Sri Lanka (ශ්‍රී ලංකාව)+94
    • Sudan (‫السودان‬‎)+249
    • Suriname+597
    • Svalbard and Jan Mayen+47
    • Swaziland+268
    • Sweden (Sverige)+46
    • Switzerland (Schweiz)+41
    • Syria (‫سوريا‬‎)+963
    • Taiwan (台灣)+886
    • Tajikistan+992
    • Tanzania+255
    • Thailand (ไทย)+66
    • Timor-Leste+670
    • Togo+228
    • Tokelau+690
    • Tonga+676
    • Tunisia (‫تونس‬‎)+216
    • Turkey (Türkiye)+90
    • Turkmenistan+993
    • Tuvalu+688
    • Uganda+256
    • Ukraine (Україна)+380
    • United Arab Emirates (‫الإمارات العربية المتحدة‬‎)+971
    • United Kingdom+44
    • United States+1
    • Uruguay+598
    • Uzbekistan (Oʻzbekiston)+998
    • Vanuatu+678
    • Vatican City (Città del Vaticano)+39
    • Venezuela+58
    • Vietnam (Việt Nam)+84
    • Wallis and Futuna (Wallis-et-Futuna)+681
    • Western Sahara (‫الصحراء الغربية‬‎)+212
    • Yemen (‫اليمن‬‎)+967
    • Zambia+260
    • Zimbabwe+263
    • Åland Islands+358
    webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

    Subscribe to our Newsletter, and get personalized recommendations.

    image not found!
    image not found!

    How to Implement MVC Architecture in Java?

    edureka.co

    preload imagepreload image