How to Generate QR Code in Java Spring Boot

Rahul Gupta
Nerd For Tech
Published in
2 min readSep 29, 2021

As we know that QR Codes are becoming the most widely recognized 2D barcodes worldwide. The big benefit of the QR code is that we can store large amounts of data in a limited space.

Here, In this article, we will learn how to generate a QR code using Java Spring boot.

http://localhost:8080

Create a Java spring Boot project and add spring web starter dependencies in the pom.xml

  1. Spring Boot web starter
  2. Thymeleaf : Thymeleaf is a Java-based library used to create a web application. It provides good support for serving an XHTML/HTML5 in web applications.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Add ZXing Library to generate the QR Code in the pom.xml

We are using ZXing Library to generate the QR Code, so it is required to add two more dependencies in the pom.xml file as shown below.

  1. Core image dependency
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>

2. Java Client dependency.

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>

Till here your pom.xml file should look like this :

Create a class for QR Code Generator name QRCodeGenerator.java

Add two static functions in the QRCodeGenerator class.

  1. Generate QR Code Image
    This function is used to generate the QR Code in image form and this will save the image in the specified path.
  2. Generate QR Code ByteArray
    This function will generate the QR Code in the form of a byte array.

We can change the color of the QR Code by mentioning the colors in the MatrixToImageConfig Object.

MatrixToImageConfig con = new MatrixToImageConfig( foregroundColor , backgroundColor) ;

Create a Controller class name MainController.java

In this class, we will create a method “getQRCode” with the GetMapping (“/”). This method will call the function that we have created in QRCodeGenerator class to get the Image or the Byte Array for the QR code.

We have returned a file name called qrcode.html that will display the QRCode. This qrcode.html is located in resources/templates/qrcode.html

Run the application

  1. Go to the browser and hit: http://localhost:8080
  2. Go inside the “src/main/resources/static/img/” folder to see the QR Code image.

Github Repository for full Reference

https://github.com/rahul26021999/QrCode-JavaSpringBoot

--

--