How To Create QR Codes in Java & Servlet

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Hello World QR Code in Java

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:

zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)

Also download the QRGen JAR File from their download page.

Include these JAR files in your Classpath and execute following Java code to generate QR 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
		}
	}
}

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file C:\QR_Code.JPG.

Download Source Code

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Hello World” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs 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();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Hello World” string with the URL you want to encode in QR Code. Below is the code snippet:

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

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.

File: index.jsp

<html>
<head>
<title>QR Code in Java Servlet - viralpatel.net</title>
</head>
<body>
	
	<form action="qrservlet" method="get">
		<p>Enter Text to create QR Code</p>
		<input type="text" name="qrtext" />
		<input type="submit" value="Generate QR Code" />
	</form>
</body>
</html>

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: 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();
	}
}

The below web.xml simply maps QRCodeServlet.java with /qrservlet URL.

File: 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>

Download Source Code

QR_Code_Servlet.zip (340 KB)

Output

qr-code-java-servlet-index

qr-code-java-servlet-image


Conclusion

Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this :)



64 Comments

  • JPW 17 April, 2014, 14:56

    This worked for me – thanks for the clear instructions and demonstration !

  • emma 1 May, 2014, 14:43

    When I use and do whatever you did My browser doesnot display the qr code it instead throws an exception i.e it shows
    ” javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    root cause

    java.lang.NoClassDefFoundError: net/glxn/qrgen/QRCode
    QR.QRCodeServlet.doGet(QRCodeServlet.java:18)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    root cause

    java.lang.ClassNotFoundException: net.glxn.qrgen.QRCode
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1132)
    QR.QRCodeServlet.doGet(QRCodeServlet.java:18)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    What could be the problem?

  • Lennonerd 29 May, 2014, 13:15

    integrate qr code scanner for android in c#
    http://www.keepdynamic.com/dotnet-barcode-reader/qr-code.shtml

  • Johnny 10 June, 2014, 18:32

    Hello!
    please, i use this source code to generate QR code as servlet and it works, but i need to recuperate the image in image tag as

    <image src=" ">

    .
    and thanks for help

  • Showeb 9 July, 2014, 19:38

    Very nice examples.

  • Chandan 26 September, 2014, 10:48

    Hi,
    Please anyone let me know how to read a contents of a file and generate the QR codes

    Thanks

  • bobbell2 10 October, 2014, 14:35

    Hello,i find a sample code of how to generate qr qode in java class,but i am not professional in this files,can anyone tell me is this code available?
    Sample code:(http://www.keepautomation.com/products/java_barcode/barcodes/qrcode.html)

    public static void main(String[] args)
    {

    BarCode barcode = new BarCode();

    barcode.setCodeToEncode(“123456789″);
    barcode.setSymbology(IBarCode.QRCODE);
    barcode.setQrCodeDataMode(IBarCode.QR_MODE_AUTO);
    barcode.setQrCodeEcl(IBarCode.QR_ECL_L);
    barcode.setQrCodeVersion(1);

    try
    { barcode.draw(“c://qrcode.gif”);

    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }

  • Deeptomay Roy 20 October, 2014, 14:34

    it shows
    ” javax.servlet.ServletException: Servlet execution threw an exception”

    Please help .

  • Kat Rollo 23 October, 2014, 11:39

    For those who might encounter “NoSuchMethodError”, it means the qrgen jar is not compatible with the zxing 1.7 jars.

    To fix this, it’s either you
    (1) get the updated zxing jars to work with the latest qrgen jar or
    (2) get a lower version of qrgen to work with the zxing 1.7 jars.

    I took option 2 and I can confirm qrgen-1.2.jar works with the zxing version on this page.

    The QRGen download link also no longer exists, the new download page can be found at
    http://search.maven.org/#browse|-852965118

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *