Spring Boot Web Generate and Display QR Code

This Spring Boot tutorial to show you step by step to implement a Spring Boot web application which generate QR code from user input and display the QR code via a web page.

Table of contents

  1. Create New Spring Boot Web Project
  2. Add ZXing Core and ZXing Java SE Extensions libraries to the Spring Boot project
  3. Write QR Code Service Interface and Class
  4. Write Controller Class and HTML Views
  5. Complete Source Code and run the Web Application
  6. Download The Source Code

Create New Spring Boot Web Project

Open IntelliJ IDEA, select the menu File > New > Project.

On the New Project dialog, select Spring Initializr and click Next button.

Spring Boot Web Generate and Display QR Code

On the Spring initializr Project Settings dialog input the new project information as below and click Next button.

  • Group: dev.simplesolution
  • Artifact: spring-boot-generate-display-qr-code
  • Version: 1.0.0
  • Name: spring-boot-generate-display-qr-code
  • Description: Spring Boot Web Generate and Display QR Code
  • Package: dev.simplesolution.generateqr

Spring Boot Web Generate and Display QR Code

On the Dependencies dialog, select below dependencies and click Next button.

  • Spring Web
  • Thymeleaf

Spring Boot Web Generate and Display QR Code

Select the location for your project and click Finish button to create new Spring Boot project.

Spring Boot Web Generate and Display QR Code

You can also create new Spring Boot project using Spring Initializr online tool at start.spring.io as below screenshot.

Spring Boot Web Generate and Display QR Code

Add ZXing Core and ZXing Java SE Extensions libraries to the Spring Boot project

To generate the QR code image we use the ZXing library. To use ZXing library in the Maven project, add the following dependency to the pom.xml file.

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>

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

The complete pom.xml look like this.

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>dev.simplesolution</groupId>
    <artifactId>spring-boot-generate-display-qr-code</artifactId>
    <version>1.0.0</version>
    <name>spring-boot-generate-display-qr-code</name>
    <description>Spring Boot Web Generate and Display QR Code</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

If you are using Gradle, add the following dependency to the build.gradle file.

implementation group: 'com.google.zxing', name: 'core', version: '3.4.1'

implementation group: 'com.google.zxing', name: 'javase', version: '3.4.1'

Write QR Code Service Interface and Class

At this step we implement service class to generate QR image and return QR image as an array of bytes.

Create a new package named dev.simplesolution.generateqr.service and add new interface QRCodeService as below.

src/main/java/dev/simplesolution/generateqr/service/QRCodeService.java

package dev.simplesolution.generateqr.service;

public interface QRCodeService {

    byte[] generateQRCode(String qrContent, int width, int height);

}

Create a new package named dev.simplesolution.generateqr.service.impl and implement a class named QRCodeServiceImpl as following code.

src/main/java/dev/simplesolution/generateqr/service/impl/QRCodeServiceImpl.java

package dev.simplesolution.generateqr.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import dev.simplesolution.generateqr.service.QRCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class QRCodeServiceImpl implements QRCodeService {

    private Logger logger = LoggerFactory.getLogger(QRCodeServiceImpl.class);

    @Override
    public byte[] generateQRCode(String qrContent, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (WriterException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}

Write Controller Class and HTML Views

In this step we implement a new Controller class which expose 3 endpoints.

  • The index endpoint to show the form allow user input content to generate QR code.
  • The show QR code endpoint to show the HTML page which contains img tag that represent the generated QR code image.
  • The generate QR code endpoint to receive a text as QR code content and return QR code image.

Add a new Java package named dev.simplesolution.generateqr.controller and implement QRCodeController class as following Java code.

src/main/java/dev/simplesolution/generateqr/controller/QRCodeController.java

package dev.simplesolution.generateqr.controller;

import dev.simplesolution.generateqr.service.QRCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class QRCodeController {

    @Autowired
    private QRCodeService qrCodeService;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/showQRCode")
    public String showQRCode(String qrContent, Model model) {
        model.addAttribute("qrCodeContent", "/generateQRCode?qrContent=" + qrContent);
        return "show-qr-code";
    }

    @GetMapping("/generateQRCode")
    public void generateQRCode(String qrContent, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        byte[] qrCode = qrCodeService.generateQRCode(qrContent, 500, 500);
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(qrCode);
    }
}

Next step we add HTML views below to resources/templates directory un

  • index.html to show the index page which allow user input content to generate QR code.
  • show-qr-code.html to display QR code with img tag.

src/main/resources/templates/index.html

<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot Web Generate QR Code</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <h1>Generate QR Code</h1>
    <form method="POST" enctype="multipart/form-data" action="/showQRCode">
        <div class="mb-3">
            <label for="qrContent" class="form-label">Enter your content to generate QR code</label>
            <input type="text" class="form-control form-control-lg" id="qrContent" name="qrContent" required>
        </div>
        <div class="mb-3">
            <button type="submit" class="btn btn-primary">Generate QR Code</button>
        </div>
    </form>
</div>
</body>
</html>

src/main/resources/templates/show-qr-code.html

<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot Web Generate QR Code</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <a href="/" class="btn btn-link">Back to home</a>
    <br />
    <img th:src="${qrCodeContent}" />
</div>
</body>
</html>

Complete Source Code and run the Web Application

Finally we have the complete application with source code structure as below.

Spring Boot Web Generate and Display QR Code

Run the application and open http://localhost:8080/ on your browser to access the web page as below.

Spring Boot Web Generate and Display QR Code

Input the content you want to generate QR code to the text field and hit Generate QR Code to generate the QR code image as below.

Spring Boot Web Generate and Display QR Code

Download The Source Code

The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-generate-display-qr-code

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-generate-display-qr-code.git

or download at:

Download Source Code

Happy Coding 😊

Generate QR Code in Java using ZXing

Read QR Code from Image File or Base64 String in Java using ZXing

Spring Boot Web Upload and Read QR Code Image

Spring Boot Generate QR Code Image Files