Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Comparison of Cryptocurrencies using REST API

Spring MVC allows you to create web applications that can consume RESTful services. In this example, let's design a simple Spring MVC application to compare cryptocurrency prices using a RESTful API. We'll be using the CoinGecko API for this purpose as it's free and doesn't require an API key.

1. Maven Dependencies

Add the required dependencies in pom.xml.

<dependencies>
    <!-- Spring Web MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    
    <!-- Spring Web for RESTful service -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.10</version>
    </dependency>

    <!-- JSON Processing -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.3</version>
    </dependency>
</dependencies>

2. Model

Create a model for the cryptocurrency data.

public class Cryptocurrency {
    private String id;
    private String name;
    private String current_price;

    // Getters and setters
}

3. Service

Create a service to fetch and process cryptocurrency data.

@Service
public class CryptocurrencyService {
    
    private final String API_URL = "https://api.coingecko.com/api/v3/coins/markets";
    
    @Autowired
    private RestTemplate restTemplate;

    public Cryptocurrency getPrice(String cryptoName) {
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(API_URL)
            .queryParam("vs_currency", "usd")
            .queryParam("ids", cryptoName)
            .queryParam("order_by", "market_cap_desc")
            .queryParam("limit", "10")
            .queryParam("sparkline", "false")
            .queryParam("price_change_percentage", "24h");

        ResponseEntity<Cryptocurrency[]> response = restTemplate.getForEntity(
            uriBuilder.toUriString(), 
            Cryptocurrency[].class
        );

        return response.getBody()[0];
    }
}

4. Controller

Design a controller to handle user requests.

@Controller
@RequestMapping("/crypto")
public class CryptocurrencyController {

    @Autowired
    private CryptocurrencyService cryptocurrencyService;

    @GetMapping("/compare")
    public String compare(@RequestParam("name") String cryptoName, Model model) {
        Cryptocurrency crypto = cryptocurrencyService.getPrice(cryptoName);
        model.addAttribute("crypto", crypto);
        return "cryptoDetails";
    }
}

5. View

Create a JSP to display the cryptocurrency data (cryptoDetails.jsp).

<html>
<body>
    Cryptocurrency: ${crypto.name}
    <br/>
    Current Price (in USD): ${crypto.current_price}
</body>
</html>

6. Spring Configuration

Configure Spring MVC and RestTemplate bean.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.demo")
public class AppConfig implements WebMvcConfigurer {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        registry.viewResolver(resolver);
    }
}

With this setup, users can visit /crypto/compare?name=bitcoin to view the current price of Bitcoin in USD. Similarly, you can expand this functionality to include more cryptocurrencies, different currencies, or even different metrics.