Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaData Transfer Object (DTO) in Spring MVC with Example

Data Transfer Object (DTO) in Spring MVC with Example

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.neveropen</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.neveropen.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.neveropen.calculator.config package. Below is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java




package com.neveropen.calculator.config;
  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
  
@Configuration
@ComponentScan(basePackages = "com.neveropen.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.neveropen.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.neveropen.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.neveropen.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.neveropen.calculator.controllers package. Below is the code for the AppController.java file.

File: AppController.java file

Java




package com.neveropen.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.neveropen.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.neveropen.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.neveropen.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.neveropen.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.

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments