Home Java javaTutorial How to create QR code using java and servlet

How to create QR code using java and servlet

Nov 26, 2016 pm 12:01 PM
java servlet QR code

Thanks to smartphones, QR codes are becoming more and more mainstream and they are becoming more and more useful. From bus shelters, product packaging, home improvement stores, cars to many websites, they all integrate QR codes on their web pages to allow people to find them quickly. With the growing number of smartphone users, the use of QR codes is rising exponentially.

Let’s take a look at a brief overview of QR codes and how to generate them in Java.

Introduction to QR code

QR code (Quick Response code) is a type of matrix barcode (or QR code), which was first designed for the automotive industry. Thanks to their fast readability and large storage capacity, QR codes are becoming popular outside the automotive industry. The pattern consists of black squares arranged in an orderly manner on a white background. The encoded data can be one of four standard data (numeric, alphanumeric, byte/binary, Chinese characters), but can also be extended to implement more data.

Toyota subsidiary Denso Wave invented the QR code in 1994 to track vehicles on the production line. Since then, QR codes have become the most popular literal translation of 2D barcodes. QR codes are designed to support high-speed decoding of content.

Hello World implementing QR code in Java

Zebra Crossing (ZXing) is a great tool that can be used to generate and parse QR codes on almost all platforms (Android, JavaSE, iPhone, RIM, Symbian) Open source library. However, if you just want to generate a simple QR code, it is not easy to use it.

QRGen is developed on the basis of ZXing. This library makes generating QR codes using Java a piece of cake. It depends on ZXing, so when generating patterns, you need the jar packages of both ZXing and QRGen.

You will not find the jar file on the ZXing download page. You have to compile it yourself from the source code. I will generate it for you. The link is here.

zxing-core-1.7.jar (346 KB)

zxing-javase-1.7.jar (21 KB)

QRGen’s jar package can be downloaded from the official website.

Import them into the classpath and then execute the following Java code:

package net.viralpatel.qrcode;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
 
public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream();
 
        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:QR_Code.JPG"));
 
            fout.write(out.toByteArray());
 
            fout.flush();
            fout.close();
 
        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
}
Copy after login

These codes are very intuitive. We use the QRCode class to generate the QR code stream and write it to the file C:QR_Code.jpg through the byte stream.

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan it with your iPhone or Android QR code tool, you will see a cool "Hello World"

Except using QRGen API to generate data streams, we can also use the following API to create QR codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();
 
// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();
 
// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();
 
// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();
Copy after login

Generate QR codes for website links (URL) in Java

The most common application of QR codes is to create a specific URL for a website Web or download pages bring traffic. As such, QR codes often encode a URL or website address that users can scan with their phone's camera and open in their browser. URLs can be encoded directly in QR codes. In the Hello World example above, just replace the string "Hello World" with the URL that needs to be encoded. Here is the code snippet:

ByteArrayOutputStream out = QRCode.from("http://viralpatel.net").to(ImageType.PNG).stream();
Copy after login

QR code in Servlet

Most of the time, you need to dynamically generate some QR codes on the website. We have seen how easy it is to generate QR codes in Java. Now, let's see how to integrate generating QR codes into Java Servlet.

The following is a simple HTTP Servlet using QRGen and ZXing libraries to create QR codes. The content of the QR code can be provided by the user.

The index.jsp file contains a simple HTML form with input boxes and a submit button. The user can enter the text he wishes to encode and submit it.

index.jsp

<form action="qrservlet" method="get">
 <p>Enter Text to create QR Code</p>
 <input name="qrtext" type="text">
 <input value="Generate QR Code" type="submit">
</form>
Copy after login

The secret is in QRCodeServlet.java. Here we use QRGen and ZXing to generate QR code from the text obtained from request.getParameter. Once the QR code stream is generated, we write it into the response and set the appropriate content-type.

QRCodeServlet.java

package net.viralpatel.qrcodes;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
 
public class QRCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
 
        String qrtext = request.getParameter("qrtext");
 
        ByteArrayOutputStream out = QRCode.from(qrtext).to(ImageType.PNG).stream();
 
        response.setContentType("image/png");
        response.setContentLength(out.size());
 
        OutputStream outStream = response.getOutputStream();
 
        outStream.write(out.toByteArray());
 
        outStream.flush();
        outStream.close();
    }
}
Copy after login

Use web.xml to map the /qrservlet request to QRCodeServlet.java.

web.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 
    <display-name>QR_Code_Servlet</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <servlet>
        <servlet-name>QRCodeServlet</servlet-name>
        <servlet-class>net.viralpatel.qrcodes.QRCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QRCodeServlet</servlet-name>
        <url-pattern>/qrservlet</url-pattern>
    </servlet-mapping>
 
</web-app>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles