Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
Next article icon

Spring MVC - Last 24 Hour Cryptocurrency Data using REST API

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=ethinr

JSON Response:

JSON Response
 

Let us see how to get a JSON response and render it in JSP pages via a Spring MVC project. Project is prepared as a maven project.

Project Structure:

Project Structure
 

pom.xml

XML
<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                          http://maven.apache.org/maven-v4_0_0.xsd">     <modelVersion>4.0.0</modelVersion>     <groupId>com.lasttwentyfour.cryptodata</groupId>     <artifactId>lasttwentyfourcryptodataRestAPI</artifactId>     <packaging>war</packaging>     <version>0.0.1-SNAPSHOT</version>     <name>lasttwentyfourcryptodataRestAPI</name>     <url>http://maven.apache.org</url>     <properties>         <failOnMissingWebXml>false</failOnMissingWebXml>         <spring-version>5.1.0.RELEASE</spring-version>     </properties>     <dependencies>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-webmvc</artifactId>             <version>${spring-version}</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-test</artifactId>             <version>${spring-version}</version>         </dependency>          <!-- JSTL Dependency -->         <dependency>             <groupId>javax.servlet.jsp.jstl</groupId>             <artifactId>javax.servlet.jsp.jstl-api</artifactId>             <version>1.2.1</version>         </dependency>         <dependency>             <groupId>taglibs</groupId>             <artifactId>standard</artifactId>             <version>1.1.2</version>         </dependency>          <!-- Servlet Dependency -->         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>3.1.0</version>             <scope>provided</scope>         </dependency>          <!-- JSP Dependency -->         <dependency>             <groupId>javax.servlet.jsp</groupId>             <artifactId>javax.servlet.jsp-api</artifactId>             <version>2.3.1</version>             <scope>provided</scope>         </dependency>         <dependency>             <groupId>com.google.code.gson</groupId>             <artifactId>gson</artifactId>             <version>2.8.6</version>         </dependency>         <dependency>             <groupId>commons-io</groupId>             <artifactId>commons-io</artifactId>             <version>2.5</version>         </dependency>         <dependency>             <groupId>junit</groupId>             <artifactId>junit</artifactId>             <version>4.12</version>             <scope>test</scope>         </dependency>     </dependencies>     <build>         <finalName>LastTwentyFourDetails</finalName>         <sourceDirectory>src/main/java</sourceDirectory>         <plugins>             <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <version>3.5.1</version>                 <configuration>                     <source>1.8</source>                     <target>1.8</target>                 </configuration>             </plugin>             <!-- This should be added to overcome Could not initialize class                   org.apache.maven.plugin.war.util.WebappStructureSerializer -->             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-war-plugin</artifactId>                 <version>3.3.2</version>             </plugin>         </plugins>     </build> </project> 

JSP page that is necessary for invocation

lastTwentyFourCryptoData.jsp

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="utf-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1">     <title>Last Twenty Four Cryptocurrency Data</title>     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>     <style type="text/css">         .main-form, .profile-area {             width: 500px;         }         .main-form {             margin: 50px auto 0px;         }         .profile-area {             margin: 10px auto;         }         .main-form section, .profile-area section {             margin-bottom: 15px;             background: #ffb891;             box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);         }         .main-form section {             padding: 30px;         }         .profile-area section {             padding: 30px 30px 30px;         }         .profile-area section > div {             text-align: center;         }         .main-form h3 {             margin: 0 0 15px;         }         .form-control, .btn {             min-height: 38px;             border-radius: 2px;         }         .btn {             font-size: 15px;             font-weight: bold;             font-family: verdana;         }         .hideElement {             display: none;         }         table, th, td {   border: 1px solid white;   border-collapse: collapse; } th, td {   background-color: #a0e040; }     </style> </head> <body> <div class="main-form" id="main-form">     <section>         <h5 class="text-center">Enter a Cryptocurrency to know about its 24 hour data </h5>         <div class="form-group">             <input id="symbol" type="text" class="form-control" placeholder="Enter a Cryptocurrency(btc/eth/icx/bnb etc) ..." required="required">         </div>         <!--          <h5 class="text-center">Enter a comparison Cryptocurrency </h5>         <div class="form-group">             <input id="tsyms" type="text" class="form-control" placeholder="Enter a comparison Cryptocurrency ..." required="required">         </div> -->         <div class="form-group">             <button onclick="loadData()" class="btn btn-primary btn-block">Fetch 24 Hours Crypto Data</button>         </div>     </section> </div> <div class="profile-area hideElement" id="profile-area">     <section>         <div id="loader" class="hideElement">             <div class="spinner-border" role="status">                 <span class="sr-only">Loading...</span>             </div>         </div>         <div id="profile" class="hideElement">         <center>             <table border = "2" col>             <tr>                 <th><strong><span id="cryptosymbol">   </span> Price In INR </strong></th>             </tr>             <tr><td><strong>OpenPrice : <span id="openPrice"></span></strong></td></tr>             <tr><td><strong>LastPrice : <span id="lastPrice"></span></strong></td></tr>             <tr><td><strong>BidPrice : <span id="bidPrice"></span></strong></td></tr>                              </table>             </center>         </div>     </section> </div> </body> <script>     function loadData() {         document.getElementById("profile-area").classList.remove("hideElement");         document.getElementById("loader").classList.remove("hideElement");         document.getElementById("profile").classList.add("hideElement");         var symbol = document.getElementById("symbol").value;         if(symbol != "" && symbol != null) {             var xhttp = new XMLHttpRequest();             xhttp.onreadystatechange = function() {                 if (this.readyState == 4 && this.status == 200) {                     var jsonResponse = JSON.parse(this.responseText);                     document.getElementById("cryptosymbol").innerHTML = jsonResponse.cryptosymbol                     ;                     document.getElementById("openPrice").innerHTML = jsonResponse.openPrice;                     document.getElementById("lastPrice").innerHTML = jsonResponse.lastPrice;                     document.getElementById("bidPrice").innerHTML = jsonResponse.bidPrice;                     document.getElementById("loader").classList.add("hideElement");                     document.getElementById("profile").classList.remove("hideElement");                 }             };             xhttp.open("GET", "getCryptodataForLastTwentyFour?cryptoSymbol=" + symbol + "inr", true);                          xhttp.send();             console.log("done");         } else {             console.log("Enter a cryptocurrency...")         }     } </script> </html> 

Output:

 

Let us provide any symbol of cryptocurrencies. A few examples are provided in the below table.

Cryptocurrency

Symbol

Bitcoinbtc
Ethereumeth
TetherUSDT
XRPXRP
LitecoinLTC

Let us see for eth (Ethereum)

 

Important java files that need to be looked

AppConfig.java

Java
package com.lasttwentyfour.cryptodata.config;  import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView;  @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.lasttwentyfour.cryptodata" }) public class AppConfig {      @Bean     public InternalResourceViewResolver resolver() {         InternalResourceViewResolver resolver = new InternalResourceViewResolver();         resolver.setViewClass(JstlView.class);         resolver.setPrefix("/");         resolver.setSuffix(".jsp");         return resolver;     }  } 

SpringMvcDispatcherServletInitializer.java

Java
package com.lasttwentyfour.cryptodata.config;  import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  public class SpringMvcDispatcherServletInitializer            extends AbstractAnnotationConfigDispatcherServletInitializer {       @Override     protected Class<?>[] getRootConfigClasses() {         return null;     }       @Override     protected Class<?>[] getServletConfigClasses() {         return new Class[] { AppConfig.class };     }       @Override     protected String[] getServletMappings() {         return new String[] { "/" };     }   } 

CryptocurrencyLastTwentyFourHourController.java

Java
package com.lasttwentyfour.cryptodata.controller;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.StringTokenizer;  import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;  import com.google.gson.Gson; import com.google.gson.JsonObject;  @Controller public class CryptocurrencyLastTwentyFourHourController {     @RequestMapping("/getCryptodataForLastTwentyFour")     public @ResponseBody     JsonObject getCryptodataForLastTwentyFour(String cryptoSymbol) throws IOException {          JsonObject jsonObject = new JsonObject();         jsonObject = getCryptoDetailsForLastTwentyFour(cryptoSymbol);         String data = jsonObject.toString().replaceAll("^\"|\"$", "");         StringTokenizer jsonTokenizer = new StringTokenizer(data,",");         String internalData[];         String expectedCryptocurrencyOutput = null;                 while (jsonTokenizer.hasMoreTokens()) {               expectedCryptocurrencyOutput = jsonTokenizer.nextToken();             internalData = StringUtils.split(expectedCryptocurrencyOutput,":");             System.out.println(internalData[0]+internalData[1]);             if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("baseAsset")) {                 jsonObject.addProperty("cryptosymbol",internalData[1].substring(1,internalData[1].length()-1));                              }             if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("openPrice")) {                 jsonObject.addProperty("openPrice",internalData[1].substring(1,internalData[1].length()-1));             }             if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("lastPrice")) {                 jsonObject.addProperty("lastPrice",internalData[1].substring(1,internalData[1].length()-1));             }             if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("bidPrice")) {                 jsonObject.addProperty("bidPrice",internalData[1].substring(1,internalData[1].length()-1));             }                }         return jsonObject;     }      private JsonObject getCryptoDetailsForLastTwentyFour(String cryptoSymbol) throws IOException {         StringBuilder responseData = new StringBuilder();         JsonObject jsonObject = null;          URL url = null;                  // url = new URL("https://api.wazirx.com/sapi/v1/tickers/24hr");         url = new URL("https://api.wazirx.com/sapi/v1/ticker/24hr?symbol="+cryptoSymbol);          HttpURLConnection con = (HttpURLConnection) url.openConnection();         con.setRequestMethod("GET");         con.setRequestProperty("User-Agent", "Mozilla/5.0");         int responseCode = con.getResponseCode();          System.out.println("\nSending 'GET' request to URL : " + url);         System.out.println("Response Code : " + responseCode);          try (BufferedReader in = new BufferedReader(                 new InputStreamReader(con.getInputStream()))) {               String line;              while ((line = in.readLine()) != null) {                 responseData.append(line);             }              jsonObject = new Gson().fromJson(responseData.toString(), JsonObject.class);                      }         System.out.println(jsonObject);         return jsonObject;     } } 

Another Example:

 

Next Article
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API

P

priyarajtt
Improve
Article Tags :
  • Java
  • Project
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Difference Between ApplicationContext and WebApplicationContext in Spring MVC
    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. W
    3 min read
    Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are goi
    4 min read
    Difference Between @Controller and @Service Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.  Spring @Control
    5 min read
    Difference Between @Controller and @RestController Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not directly affect the operation of the code they annotate. It does not change the action of the compiled program. Understanding the differ
    3 min read
    Spring MVC - @RequestParam Annotation
    The @RequestParam annotation is one of the most commonly used annotations in Spring MVC for handling HTTP request parameters. @RequestParam annotation enables Spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Key features of @RequestParam annotation
    5 min read
    Query String and Query Parameter in Spring MVC
    According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a pag
    6 min read
    How to Make Post Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make Delete Request in Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make get() Method Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    3 min read
    Spring @RequestMapping Annotation with Example
    The @RequestMapping annotation in Spring MVC is one of the most important annotations used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to the handler method
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences