Skip to content
Related Articles

Related Articles

Spring Boot – Starter Web

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 14 Feb, 2022

Today most of the applications demand Model-View-Controller (MVC) architecture to meet the various needs like handling user data, making application efficient, to provide dynamic nature to applications. It was basically used for building desktop graphical user interfaces (GUIs), but now is becoming more popular for building web-based applications. MVC is not a technology stack, rather it is an architectural pattern that provides three important logical components Model, View, and Controller.

  1. Model: A Model is the data and logic handling the data. It represents the data that’s get transferred among controllers or any other logic. The controller can retrieve data (model) from a database and/or from the user.
  2. View: A View is a part of an application that presents the model data. Data is of database form or from user input. It is an output presentation to users from manipulated data like tables, charts, diagrams, etc.
  3. Controller: A Controller is responsible for handling user interaction with the application. It gets mouse and keyboard inputs from users and changes the Model and View with respect to inputs.
MVC Design Pattern

MVC Architecture

Advantages of MVC Architecture

  1. Easy code maintenance eases the scaling of applications.
  2. Testing can be performed separately from the user.
  3. Model-View-Controller reduces the complexity.
  4. It is Search Engine Optimization (SEO) friendly.
  5. The controller itself allows the logical grouping of related actions together.

At the center of the Spring’s essential features is the Spring MVC – Spring’s web framework. It is packaged in the ‘Spring Web’ starter. Spring MVC can also be used to create REST APIs which produce non-HTML output (e.g – JSON, XML, etc).

To embed Started Web in Spring Application:

Spring Tool Suite (STS) -> Go To File -> New -> Spring Starter Project -> Next  -> Spring Web -> Next -> Finish

You can also add Starter Web dependency.

Maven -> pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradle -> build.gradle

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
}

Spring MVC Workings

Project Structure – Maven

pom.xml (project configuration)

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> 
    </parent>
    <groupId>sia</groupId>
    <artifactId>GFG-Starter-Web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GFG-Starter-Web</name>
    <description>Spring Boot Starter Web</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


GfgStarterWebApplication.java (Bootstrapping of application)

Java




package gfg;
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
@SpringBootApplication
public class GfgStarterWebApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(GfgStarterWebApplication.class, args);
    }
    
}


UserModel.java (Model)

  • Java beans require getter and setter methods to update and access the variables.
  • ‘Lombok’ java library automates the process of making Getter and Setter method with ‘@Data’ annotation.
  • To include Lombok in the project, add the following dependency:
Maven -> pom.xml

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Java




package gfg;
  
import lombok.Data;
  
@Data
public class UserModel {
    public String userText;
}


view.html (View – Thymeleaf Template)

Reads the user input which gets bound to UserModel, thus creating a Model data. After submitting, it passes the Model data to the Controller.

HTML




<!DOCTYPE html>
<html>
  
<head>
<title>GeeksforGeeks</title>
</head>
  
 <body>
  
    <h1 style="color:forestgreen" th:text="${Controller1}">attributeValue will be placed here</h1
    <h1 style="color:forestgreen" th:text="${Controller2}">attributeValue will be placed here</h1>
    <h2 style="color:forestgreen" th:text="${message}"> attributeValue will be placed here </h2>
  
    <form method="POST" th:object="${userModel}">
  
            <label for="userText">Type Message : </label><br/>
            <input type="text" th:field="*{userText}"/>
  
            <input type="submit" value="Go"/>
  
    </form >
  
 </body>
</html>


MVCController1.java (Controller)

Some useful annotations used for Controllers are:

  1. @Controller – It is a specialized version of @Component annotation indicating that a class is a ‘Controller’ which is automatically detected while classpath scanning. It works concurrently with an annotation like @RequestMapping, handler method annotations like @GetMapping, @PostMapping, etc.
  2. @RequestMapping – It is used to map web requests onto respective methods of request handling classes. It can be used both on a Class level as well as Method level. On the method level HTTP, specific annotations should be used.
  3. @GetMapping – It maps HTTP GET web requests onto a specific handler method. It’s alternative is ‘@RequestMapping( method=RequestMethod.GET )’.
  4. @PostMapping – It maps HTTP POST web requests onto a specific handler method. It’s alternative is ‘@RequestMapping( method=RequestMethod.POST )’.
  5. @SessionAttributes – It lists the model attributes(data) that should be stored in session and used by specific annotated handler methods.
  6. @ModelAtrribute – It binds method parameter or method return value to the named model attribute which is exposed to a web view.

This controller has two methods:

  1. get() – This method is called on GET request which binds Model data and returns a view.
  2. post() – This method gets Model data from the user’s POST request which is to be used by other controllers and redirects to MVCController2.java.

Java




package gfg;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.SessionAttributes;
  
@Controller
@SessionAttributes("userModel")
@RequestMapping("MVC-1")
public class MVCController1 {
      
    @GetMapping
    public String get(Model model) {
        model.addAttribute("Controller1","You are in Controller-1");
        model.addAttribute("userModel", new UserModel());
        return "view";    
    }
      
    @PostMapping
    public String post(@ModelAttribute("userModel") UserModel userModel, Model model,RedirectAttributes redirectAttributes) {    
        redirectAttributes.addFlashAttribute("user", userModel);
        return "redirect:/MVC-2";
    }
}


Output: view.html

Output

View returned after ‘GET’ request on MVCController1.java

MVCController2.java (2nd Controller)

This controller has two methods:

  1. get() – This method uses Model data forwarded by MVCController’s post() method and with other Model data returns a view.
  2. post() – This method gets Model user data, forwards it, and redirects to RestMVCController.

Java




package gfg;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.SessionAttributes;
  
@Controller
@SessionAttributes("userModel")
@RequestMapping("/MVC-2")
public class MVCController2 {
      
    @GetMapping
    public String get(@ModelAttribute("user") UserModel message, Model model) {
        model.addAttribute("Controller2","You are in Controller-2");
        model.addAttribute("message", message.getUserText());
        model.addAttribute("userModel", new UserModel());
        return "view";
    }
      
    @PostMapping
    public String post(@ModelAttribute("userModel") UserModel userModel, Model model,RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", userModel);
        return "redirect:/Rest";
    }
      
}


Output: view.html

Output

View returned by MVCController2.java

Spring MVC workings with REST API

RestMVCController.java (REST API)

Some important annotations used are:

  1. @RestController – It is the combination of @RequestMapping and @ResponseBody annotations which return data in the response body rather than as a view.
  2. @CrossOrigin – It is used to allow cross-origin requests on handler classes and/or on handler methods to consume data.

Java




package gfg;
  
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.bind.annotation.SessionAttributes;
  
@RestController
@SessionAttributes("userModel")
@RequestMapping(path="/Rest", produces="application/json")
@CrossOrigin(origins="*"
public class RestMVCController {
  
    @GetMapping
    public UserModel get(@ModelAttribute("message") UserModel user, SessionStatus sessionStatus) {
          
        // cleans up the stored 
        // session attributes (data)
        sessionStatus.setComplete(); 
        return user;
    }
}


Output

Output

Returns Model data in Response (JSON literal)

Note: Spring framework’s back end REST API can work in combination with front end framework technologies like Angular, React, etc which can request for data and also provides the data. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!