QR Code Generator with Spring Boot and ReactJS

PabasaraRathnayake
7 min readJul 31, 2023

During my internship period, I had the exciting opportunity to work on a research and development project. In this project, I successfully created a QR Code Generator using a Spring Boot application as the backend and a ReactJS application as the frontend. In this blog post, I’ll walk you through the step-by-step process of how I accomplished this task.

I have linked the source code and a demonstration at the end of this blog.

1. Setting up the Spring Boot Application

To begin, I set up a Spring Boot application to serve as the backend. The Spring Boot framework is excellent for building robust and scalable web applications quickly. I created a new Spring Boot project and set up the necessary dependencies using Maven.

Dependencies

  1. spring-boot-started-web: This dependency includes all the necessary components to build a web application using Spring Boot. It provides support for embedded Tomcat, Spring MVC, and other web-related features.
  2. spring-boot-started-test: This dependency is used for writing unit tests and integration tests in your Spring Boot application. It includes libraries and utilities like JUnit, Mockito, and Spring Test. (If you are writing test cases)

Here’s how the dependencies should appear in pom.xml

 <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

2. Creating the Controller

In the Spring Boot application, I created a single controller class called “QRController.” The controller handles incoming HTTP requests and processes the QR code generation logic. I used the @CrossOrigin(“*”) annotation to enable cross-origin requests.

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

@CrossOrigin("*")
@RestController
public class QRController {

@Autowired
QRService qrService;

@GetMapping("/qr-generator")
public String processQR() {
try {
ResultDTO result = qrService.processQR();
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(result);
} catch (Exception e) {
return "Exception found";
}
}
}
  1. @RestController: The @RestController annotation is used to mark the class as a controller in Spring Boot. It combines the @Controller and @ResponseBody annotations, indicating that the methods in this class will return the response directly in the HTTP response body.
  2. @CrossOrigin(“*”): The @CrossOrigin annotation is used to enable Cross-Origin Resource Sharing (CORS) for this controller. CORS is a security feature implemented by web browsers to prevent web pages from making requests to a different domain than the one that served the web page. By specifying “*” as the value, you are allowing any origin to access the endpoints in this controller.
  3. @Autowired: The @Autowired annotation is used to inject an instance of the QRService into the controller. This enables the controller to use the methods provided by the service class.
  4. @GetMapping(“/qr-generator”): The @GetMapping annotation is used to map HTTP GET requests to the specified endpoint (“/qr-generator”) to the processQR() method in this controller. When a client makes a GET request to “/qr-generator,” this method will be invoked to handle the request.
  5. public String processQR(): This method is responsible for processing the QR code generation logic. It returns a String representation of the result, which will be converted to a JSON response in this case.
  6. try-catch block: Inside the processQR() method, there’s a try-catch block to handle any exceptions that may occur during the QR code generation process.
  7. ResultDTO: The ResultDTO class is used to encapsulate the result of the QR code generation process. It contains a single property called qrValue, which represents the text to be converted into a QR code.
  8. Jackson’s ObjectMapper: The ObjectMapper is used to convert the ResultDTO object into a JSON representation. It serializes the ResultDTO instance into a JSON string, which will be included in the HTTP response body.

3. Designing the QRService

Next, I created an interface called “QRService” that defines the contract for the QR code generation process. The service interface contains a single method called processQR().

package com.example.demo;

public interface QRService {
ResultDTO processQR();
}
  1. @Service: The @Service annotation is used to indicate that the QRServiceImpl class is a Spring service bean. Spring will automatically discover and manage this bean during component scanning.
  2. implements QRService: The QRServiceImpl class implements the QRService interface, and therefore, it must provide an implementation for the processQR()method.
  3. ResultDTO processQR(): This is the implementation of the processQR() method from the QRService interface. Inside this method, you generate the sample QR code text and encapsulate it within a ResultDTO object.
  4. ResultDTO: The ResultDTO class is a simple POJO (Plain Old Java Object) that represents the result of the QR code generation process. It contains a single property called qrValue, which holds the generated QR code text.

4. Implementing the QRService

To complete the backend logic, I implemented the QRService interface with the QRServiceImpl class. In the processQR() method, I generated a sample QR code text and encapsulated it within a custom data transfer object (DTO) called ResultDTO.

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class QRServiceImpl implements QRService {

@Override
public ResultDTO processQR() {
ResultDTO resultDTO = new ResultDTO();
resultDTO.setQrValue("123456789|WPSLite|H34");
return resultDTO;
}

}

The QRServiceImpl class is a Spring service bean responsible for generating the QR code text. The processQR() method returns a ResultDTO object containing the generated QR code text. This implementation provides a simple example of QR code generation, where the QR code text is hardcoded. In real-world scenarios, the implementation of this method would involve more complex logic to generate QR codes based on dynamic data or business requirements.

5. Running the Spring Boot Application

With the backend set up, I ran the Spring Boot application, and it started listening on the specified port (usually 8080).

You can use a testing tool to test the API. I used Postman.

6. Setting up the ReactJS Application

Moving on to the frontend, I created a new ReactJS application. React is a popular JavaScript library for building user interfaces.

7. Installing Dependencies

Within the ReactJS project, I installed the required dependencies. Notably, I used the “qrcode.react” library to render QR codes easily.

  "dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.3.5",
"qrcode.react": "^3.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Dependencies

  1. qrcode.react library installed, you can use the QRCode component from qrcode.react to easily generate QR codes in your ReactJS application. The QRCodeGenerator component (mentioned in step 8) fetches the QR code text from the Spring Boot backend and renders the QR code using the QRCode component from the qrcode.react library.
  2. axios library is crucial in your ReactJS application for making HTTP requests to the Spring Boot backend. It allows you to fetch the QR code text and dynamically display the generated QR code in the frontend using the QRCode component from the qrcode.react library.

8. Building the QR Code Component

I designed a React component called “QRCodeGenerator.” This component uses the “useEffect” hook to fetch the QR code data from the Spring Boot backend. I utilized the `axios` library for making HTTP requests to the “/qr-generator” endpoint of the Spring Boot application.

import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode.react';
import axios from 'axios';

const QRCodeGenerator = () => {
const [qrText, setQRText] = useState("");

useEffect(() => {
const fetchData = async () => {
const result = await axios.get('http://localhost:8080/qr-generator');
console.log(result);
setQRText(result.data.qrValue);
}
fetchData();
}, []);

return (
<div>
<QRCode value={qrText} />
</div>
);
}

export default QRCodeGenerator;

The QRCodeGenerator component is a functional component written using React Hooks. Here's how it works:

  1. State Management: The component uses the useState hook to manage the qrText state, which will hold the QR code text fetched from the Spring Boot backend.
  2. Fetching Data: The useEffect hook is used to fetch the QR code text from the Spring Boot backend when the component mounts. The axios library is used to make an HTTP GET request to the /qr-generator endpoint on the backend.
  3. Rendering the QR Code: The fetched qrText is then used as the value to be encoded in the QR code. The QRCode component from the qrcode.react library is used to render the QR code on the frontend.

9. Finalizing the React App

In the “App.js” file, I imported and displayed the “QRCodeGenerator” component, which resulted in a simple yet powerful QR code generator frontend.

import './App.css';
import QRCodeGenerator from "./Components/QR-Code";
import React from "react";

function App() {
return (
<div className="App">
<h1>QR Code Generator</h1>
<QRCodeGenerator/>
</div>
);
}

export default App;

10. Scan and verify

Just use your favorite QR code scanning app to see if the code displays the same string sent from the backend. Easy, right? 📱💡🔍📊

Source code

Frontend: https://github.com/pabasaraRatnayake/qr-generator-web

Backend: https://github.com/pabasaraRatnayake/qr-generation-api

Demonstration

Conclusion:

Through this internship project, I successfully developed a QR Code Generator using Spring Boot as the backend and ReactJS as the frontend. The Spring Boot application handles QR code generation logic, while the ReactJS application fetches the QR code data and renders it beautifully as a scannable QR code.

This R&D was an excellent opportunity for me to learn about integrating different technologies and building a complete web application. I look forward to exploring more R&D projects and applying my skills to real-world scenarios in the future. Happy coding!

--

--