The Wayback Machine - https://web.archive.org/web/20240930191637/https://www.geeksforgeeks.org/data-transfer-object-dto-in-spring-mvc-with-example/
Open In App

Data Transfer Object (DTO) in Spring MVC with Example

Last Updated : 22 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you’re working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. So in this article, we are going to discuss the concept of DTO and we will also discuss the implementation of DTO with an example project in Spring MVC. 

Example Project

We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:  

 

Add the following maven dependencies and plugin to your pom.xml file. 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

<!-- plugin -->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

Below is the complete code for the pom.xml file after adding these dependencies.

File: pom.xml 

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.geeksforgeeks</groupId>
    <artifactId>simple-calculator</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-calculator Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>simple-calculator</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


Configuring Dispatcher Servlet

Before moving into the coding part let’s have a look at the file structure in the below image. 

 

So at first create an src/main/java folder and inside this folder create a class named CalculatorAppIntilizer and put it inside the com.geeksforgeeks.calculator.config package and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Refer to the below image.

 

And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation. Now inside this class, we have to just write two lines of code to Configure the Dispatcher Servlet. Before that, we have to create another class for the Spring configuration file. So, go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.geeksforgeeks.calculator.config package. Below is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
  
@Configuration
@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
  
}


And below is the complete code for the CalculatorAppIntilizer.java file. Comments are added inside the code to understand the code in more detail.

File: CalculatorAppIntilizer.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer {
  
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }
  
    // Registering the Spring config file
    @Override
    protected Class<?>[] getServletConfigClasses() {
        Class aClass[] = { CalculatorAppConfig.class };
        return aClass;
    }
  
    // Add mapping url
    @Override
    protected String[] getServletMappings() {
        String arr[] = { "/geeksforgeeks.org/*" };
        return arr;
    }
  
}


Setup ViewResolver

Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology. Read more here: ViewResolver in Spring MVC. So for setting up ViewResolver go to the CalculatorAppConfig.java file and write down the code as follows

@Bean
public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

And below is the updated code for the CalculatorAppConfig.java file after writing the code for setting up the ViewResolver. 

File: Updated CalculatorAppConfig.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
  
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
  
    // setup ViewResolver
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
  
}


Create Controller 

Go to the src/main/java folder and inside this folder create a class named AppController and put it inside the com.geeksforgeeks.calculator.controllers package. Below is the code for the AppController.java file.

File: AppController.java file

Java




package com.geeksforgeeks.calculator.controllers;
  
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
  
@Controller
public class AppController {
      
    @RequestMapping("/home")
    public String showHomePage() {
        return "welcome-page";
    }
  
}


Create View

Now we have to create a view named “welcome-page” inside the WEB-INF/view folder with the .jsp extension. So go to the src > main > webapp > WEB-INF and create a folder view and inside that folder create a jsp file named welcome-page. So below is the code for the welcome-page.jsp file. 

File: welcome-page.jsp

HTML




<html>
<head>
</head>
<body>
    <h1 align="center">Data Transfer Object (DTO) in Spring MVC with Example</h1>
      
    <hr/>
  
    <form action="process-homepage" method="get">
  
        <div align="center">
              
<p>
                <label for="num1">Enter First Number : </label> <input type="text"
                    id="num1" name="number1" />
            </p>
  
              
<p>
                <label for="num2">Enter Second Number : </label> <input type="text"
                    id="num2" name="number2" />
            </p>
  
  
            <input type="submit" value="Capture" />
  
        </div>
  
    </form>
</body>
</html>


The view is looking like this 

 

So here we want to put some values inside the label and we want to capture that value so that we can display that value on our next page after clicking on the Capture button. So how to do it? We can do it in various ways and in our previous article, we have discussed how to do it by using @RequestParam Annotation. You may refer to this article for the full explanation: How to Capture Data using @RequestParam Annotation in Spring. But in this article, we are going to discuss another approach for doing it. We are going to use the DTO concept. 

Transfer Data in Spring using a DTO (Data Transfer Object)

At first, we have to create a DTO class. So go to the src/main/java folder and inside this folder create a class named NumberInfoDTO and put it inside the com.geeksforgeeks.calculator.dto package. Below is the code for the NumberInfoDTO.java file. Comments are added inside the code to understand the code in more detail.

File: NumberInfoDTO.java

Java




package com.geeksforgeeks.calculator.dto;
  
public class NumberInfoDTO {
  
    // Declare the number of variable
    // you want to capture the value
    private String number1;
    private String number2;
  
    // Generate the getter, 
    // setter and toString method
    public String getNumber1() {
        return number1;
    }
  
    public void setNumber1(String number1) {
        this.number1 = number1;
    }
  
    public String getNumber2() {
        return number2;
    }
  
    public void setNumber2(String number2) {
        this.number2 = number2;
    }
  
    @Override
    public String toString() {
        return "NumberInfoDTO [number1=" + number1 + ", number2=" + number2 + "]";
    }
  
}


As we have written this line inside the welcome-page.jsp file

<form action="process-homepage" method="get">

So we have to create a controller with the “process-homepage” endpoint. So now come to the AppController.java file again and write down the following code inside this file.

@RequestMapping("/process-homepage")
public String showResultPage(NumberInfoDTO numberInfoDTO, Model model) {

        // writing the value to the properties
        // by fetching from the URL
        model.addAttribute("numberInfo", numberInfoDTO);

        return "result-page";
}

Related Article Link: How to Create Your First Model in Spring MVC 

Below is the updated code for the AppController.java file.

File: Updated AppController.java file

Java




package com.geeksforgeeks.calculator.controllers;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
  
import com.geeksforgeeks.calculator.dto.NumberInfoDTO;
  
@Controller
public class AppController {
  
    @RequestMapping("/home")
    public String showHomePage() {
        return "welcome-page";
    }
  
    @RequestMapping("/process-homepage")
    public String showResultPage(NumberInfoDTO numberInfoDTO, Model model) {
  
        // writing the value to the properties
        // by fetching from the URL
        model.addAttribute("numberInfo", numberInfoDTO);
  
        return "result-page";
    }
  
}


Now we have to create another view named “result-page” to display the captured values. So below is the code for the result-page.jsp file. 

File: result-page.jsp

HTML




<html>
<head>
</head>
<body>
    <h1 align="center">Data Transfer Object (DTO) in Spring MVC with Example</h1>
    <hr/>
      
<p>First Number is: ${numberInfo.number1}</p>
  
      
<p>Second Number is: ${numberInfo.number2}</p>
  
</body>
</html>


So now we have done with the coding part. Let’s run and test our application. 

Run Your Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. And run your application as shown in the below image as depicted below as follows:  

 

After that use the following URL to run your controller

http://localhost:8080/simple-calculator/geeksforgeeks.org/home

Output:

 

Now let’s put some values inside the label and click on the Capture button. Suppose here we have put 41 and 75 and whenever we click on the Capture button an URL is generated as below

http://localhost:8080/simple-calculator/geeksforgeeks.org/process-homepage?number1=41&number2=75

And you can see on the next page the values are displayed.

 



Previous Article
Next Article

Similar Reads

How to Transfer Data in Spring using DTO?
In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across
7 min read
Spring Boot - Map Entity to DTO using ModelMapper
In enterprise applications, we use RESTful services to establish the communication between client and server. The general idea is that the client sends the request to the server and the server responds to that request with some response. Generally, we have three different layers in most of the application Web Layer, Business Layer, and Database Lay
8 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Data Binding in Spring MVC with Example
Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a variable and display it as per our requirements. For
8 min read
Two-Way Data Binding in Spring MVC with Example
Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a variable and display it as per our requirements. For
7 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will w
7 min read
Spring MVC – Handling Form Validation with Spring Validator
Form validation is crucial in web applications to ensure that user input is both accurate and appropriate before processing or storing it. In Spring MVC, form validation can be efficiently managed using the Spring Validator interface and annotations. This allows for flexible and robust validation mechanisms that are easy to implement and maintain i
7 min read
Securing a Spring MVC Application with Spring Security
Securing web applications is crucial in today's world, where security threats are prevalent. Spring Security is a powerful, customizable authentication and access-control framework that is part of the larger Spring ecosystem. It helps secure Spring MVC applications by managing authentication, authorization, and other security concerns. This article
7 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
Spring MVC - Pagination with Example
We will be explaining how we can implement pagination in Spring MVC Application. This is required when we need to show a lot of data on pages. Suppose in an e-commerce site we have a lot of products but we can't show all of those on a single page, so we will show only 20 products on each page. This will help in better product tracking and a great u
3 min read
Spring MVC - Basic Example using JSTL
JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web pages. They can now simply use a tag related to th
8 min read
Spring MVC - JSTL forEach Tag with Example
JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web pages. They can now simply use a tag related to th
6 min read
Spring MVC CRUD with Example
CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as Spring boot, spring-security, etc. The term MVC stands for Model-View-Controller architecture. In this article, we will be buildi
7 min read
Spring MVC and Hibernate CRUD Example
In this article, we will be developing CRUD operations in Spring MVC and Hibernate. Hibernate is an object-relational mapping (ORM) framework. Developers use Hibernate to interact with databases using Java objects rather than SQL queries. Spring MVC is a Model-View-Controller (MVC) framework used to build web applications in Java. The Spring MVC pa
6 min read
Spring MVC @SessionAttributes Annotation with Example
In the ever-evolving world of web development, a constant challenge is to seamlessly manage data between requests. Enter Spring MVC's @SessionAttributes annotation, a powerful solution that elegantly manages the session attributes of a Spring application. This markup becomes a lifesaver when certain information must persist throughout the interacti
3 min read
Spring MVC @ModelAttribute Annotation with Example
In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can have Spring MVC supply this object to a Controller m
8 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
OpenSource REST API URL and Retrieving Data From it By Using Spring MVC
In this internet era, a lot of helper services are available in the form of REST API and mostly REST API provides us the details in the form of JSON/XML. We can use them in our applications and render the data as we like. Here is the list of a few opensource REST API URLs: API NameDescriptionURLCoinGeckoExchange rates https://api.coingecko.com/api/
6 min read
Spring MVC - Capture and Display the Data from Registration Form
This article is the continuation of this article Spring MVC - Create Registration Form using Form Tag Library, where we have successfully created a registration form using the Form Tag Library. Here in this article, we are going to explain how can we capture the data that are entered by the user and display it on our next page after clicking the Re
3 min read
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
Cryptocurrencies are a hot topic now and in the future; they may also be a payment source. Hence a lot of research is getting done. Many REST APIs are available to provide data in JSON format. We are going to see one such REST API as https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=<Need to provide the symbol of cryptocurrency> Example: http
5 min read
Returning Image/Media Data with Spring MVC
Spring MVC is a popular framework to build web applications in Java. One of the common requirements in web development is handling image or media data such as pictures, videos, or audio files. In Spring MVC, handling image or media data involves configuring a controller to receive requests for specific resources and then serving those resources to
3 min read
Customizing Data Binding in Spring MVC
Data binding in Spring MVC is mapping HTTP request parameters to Java objects. It allows us to automatically populate model objects with form input data, simplifying development. Sometimes, the default binding behavior may not suffice, and customizing the data binding process becomes essential for handling complex mappings or validations. This arti
6 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=<Provide your desi
7 min read
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private String someDataMember; Note that the flag and message a
4 min read
Spring MVC using Java based configuration
Prerequisites: MVC Design Pattern, Spring MVC with JSP ViewSpring MVC framework enables separation of modules namely Model, View and Controller and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using
5 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
Practice Tags :