(go) How to create a QR code using Java, servlet

Source: Internet
Author: User
Tags html form response code



Thanks to smartphones, QR codes are becoming mainstream and they are becoming more and more useful. From the shelters, product packaging, home improvement stores, cars to many websites, all in their own web pages integrated QR Code, let people quickly find them. As the number of smartphones is increasing, the use of QR codes is increasing exponentially.



Let's look at a brief overview of QR codes and how to build them in Java.


QR Code Introduction


The QR code (quick Response Fast Response code) is a type of matrix barcode (or QR code) that is first designed for the automotive industry. Thanks to its fast reading and large storage capacity, the QR code began to be popular outside the automotive industry. The pattern is made up of black squares arranged on a white background. Coded yes data can be one of four standard data (numbers, alphanumeric, byte/binary, Kanji), but can also be extended to achieve more data.









Toyota's subsidiary, Denso Wave, invented the QR code in 1994 to track vehicles on the production line. Since then, the QR code has become the most popular two-dimensional barcode literal translation. The QR code is designed to support high-speed decoding of content.


Implementation of the QR code in Java Hello World


Zebra Crossing (ZXing) is a great open source library that can be used to generate and parse QR codes in virtually all platforms (Android, Javase, IPhone, RIM, Symbian). However, if you just want to generate a simple QR code, it's not possible to use it.



Qrgen was developed on the basis of zxing, a library that made it a piece of cake to generate QR codes from Java. It needs to rely on zxing, so you need zxing and Qrgen jar packages when you generate patterns.



You will not find the jar file in the zxing download page. Must be compiled by the source code itself, I help you build well, link here.


    • Zxing-core-1.7.jar (346 KB)
    • Zxing-javase-1.7.jar (KB)


Qrgen jar packages can be downloaded via the official website.



Import them into Classpath and execute the following Java code:


packagenet.viralpatel.qrcode;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importnet.glxn.qrgen.QRCode;importnet.glxn.qrgen.image.ImageType;publicclassMain {    publicstaticvoidmain(String[] args) {        ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream();        try{            FileOutputStream fout =newFileOutputStream(newFile(                    "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 very intuitive. We use the QRCode class to generate the QR code stream and write to the file C:\QR_Code.jpg by byte stream.


Download source code
    • Qr_code_java.zip (339 KB)


If you open this JPEG file and sweep it with your iphone or Android QR Code tool, you'll see a cool "Hello world":)



In addition to using the Qrgen API to generate data streams, we can also use the following API to create a QR code:



// get QR file from text using defaultsFile file = QRCode.from("Hello World").file();// get QR stream from text using defaultsByteArrayOutputStream stream = QRCode.from("Hello World").stream();// override the image type to be JPGQRCode.from("Hello World").to(ImageType.JPG).file();QRCode.from("Hello World").to(ImageType.JPG).stream();// override image size to be 250x250QRCode.from("Hello World").withSize(250,250).file();QRCode.from("Hello World").withSize(250,250).stream();// override size and image typeQRCode.from("Hello World").to(ImageType.GIF).withSize(250,250).file();QRCode.from("Hello World").to(ImageType.GIF).withSize(250,250).stream();
Generate a QR code for a Web site link (URL) in Java


The most common use of QR codes is to bring traffic to a specific page or download page in your site. As a result, QR codes often encode URLs or Web site addresses, which users can scan via their mobile camera and open in their browser. The URL can be encoded directly in the QR code. In the Hello World example above, simply replace the string "Hello World" with the URL you want to encode. Here is the code snippet:


1 ByteArrayOutputStream out = QRCode.from("http://viralpatel.net").to(ImageType.PNG).stream();
The QR code in the servlet


Most of the time, you need to generate some QR codes dynamically on the website. We've seen how easy it is to generate QR codes in Java. Now, let's look at how to integrate the generated QR code into the Java servlet.



Here is a simple HTTP servlet that uses the Qrgen and zxing libraries to create a QR code. The content of the QR code can be provided by the user.



The index.jsp file contains a simple HTML form with an input box and a Submit button. The user can enter the text that he wants to use for encoding and submit it.



index.jsp


<formaction="qrservlet"method="get"> <p>Enter Text to create QR Code</p> <inputname="qrtext"type="text"> <inputvalue="Generate QR Code"type="submit"></form>


The secret is in the Qrcodeservlet.java. Here, we use Qrgen and zxing to generate QR codes from the text obtained from Request.getparameter. Once the QR code stream is generated, we write to response and set the appropriate content-type.



Qrcodeservlet.java


packagenet.viralpatel.qrcodes;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importnet.glxn.qrgen.QRCode;importnet.glxn.qrgen.image.ImageType;publicclassQRCodeServletextendsHttpServlet {    @Override    protectedvoiddoGet(HttpServletRequest request,        HttpServletResponse response)throwsServletException, 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();    }}


Use Web. XML to map the/qrservlet request to Qrcodeservlet.java.



Xml


<!--?xml version="1.0" encoding="UTF-8"?--><web-appxmlns: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







Summarize


Generating a QR code in Java is not only easy, but also very convenient. Integrating this functionality into any existing Java application is a piece of cake! In this tutorial, we learned how to generate QR codes in Java and Servlets.



I hope you'll like:)



Original link: Viralpatel translation: importnew.com-Wu Pengyu
Link: http://www.importnew.com/15028.html
[ Reprint please keep the source, translator and translation links.] ]



(go) How to create a QR code using Java, servlet


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.