Java generates a QR code (based on springboot) and deploys tomcat

I did a small project in 2023 that generated a QR code in Java and deployed it to run on Tomcat.     

  

The Java programming language and Spring framework are used, and Google's ZXing library is integrated to generate QR codes. Here are some notes about the technique and what this code does:

Introduction:

Java programming language: This code is written in Java language, which is an object-oriented programming language.
Spring framework: This code uses the Spring framework for dependency injection in Java applications and development of web applications.
ZXing library: ZXing is an open source barcode and QR code image processing library. This code uses the classes and methods in the ZXing library to generate QR codes.

 

QRCodeService class: 


        Used to generate QR codes. It provides a createQRCode method that accepts content, width and height as parameters, and returns a BufferedImage object representing the generated QR code image.

package com.qrcode.demo.service;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

@Service
public class QRCodeService {

    public BufferedImage createQRCode(String content, int width, int height) throws IOException {

        if (!StringUtils.isEmpty(content)) {
            @SuppressWarnings("rawtypes")
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
            hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距

            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                return bufferedImage;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}


QRCodeController class:

        Handle HTTP requests related to QR codes. It provides a getQRCode method for a GET request, which calls QRCodeService to generate a QR code image and writes it into the HTTP response output stream to display the QR code on the front-end page.
 

package com.qrcode.demo.controller;
import com.qrcode.demo.service.QRCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/qrcode")
public class QRCodeController {
    @Autowired
    QRCodeService qrCodeService;

    @RequestMapping(value="/getQRCode", method = RequestMethod.GET)
    public void getQRCode(HttpServletResponse response) throws IOException {
        BufferedImage image = qrCodeService.createQRCode("姓名:123",450,450);
        if (image != null) {
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            os.flush();
            os.close();
        }
    }
}

index.jsp:

Used to generate a simple page in a web application.
 

<%--
  Created by IntelliJ IDEA.
  User: 黑手双城
  Date: 2023/6/20
  Time: 15:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
%>

<html>
<head>
    <meta charset="UTF-8">
    <title>QR Code Generator</title>
    <style>
        body {
            background-color: #f2f2f2;
            font-family: Arial, sans-serif;
        }

        .container {
            width: 80%;
            margin: 0 auto;
            text-align: center;
        }

        h1 {
            font-size: 36px;
            margin-top: 50px;
        }

        img {
            margin-top: 80px;
            border: 5px solid #333;
            border-radius: 10px;
        }

        button {
            background-color: #0f4ce0;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 20px;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-top: 50px;
        }

        button:hover {
            background-color: #43eaee;
        }
        xiaoxiao {
            color: #f1e535;
            font-weight: bold;
        }

        body {
            background-color: #2caf48; /* 淡灰色 */
        }
    </style>
</head>
<body>
<div class="container">
    <h1>点击出现二维码</h1>
    <xiaoxiao> <img src="" id="qr-code" alt="看左边"> </xiaoxiao>
    <button onclick="generateQRCode()">点击</button>
</div>

<script>
    function generateQRCode() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/qrcode/getQRCode', true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            if (this.status === 200) {
                var blob = new Blob([this.response], {type: 'image/png'});
                var url = URL.createObjectURL(blob);
                document.getElementById('qr-code').src = url;
            }
        };
        xhr.send();
    }
</script>
</body>
</html>

pom.xml:

Needless to say 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.qrcode</groupId>
	<artifactId>QRcode</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>qrcodeDemo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

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

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

		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.2.1</version>
		</dependency>
		<!-- JSP支持 -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- 移除内置的tomcat -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-servlet-api</artifactId>
			<version>8.0.36</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

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


</project>

QrcodeDemoApplication:

This restart class makes it start external Tomcat
 

package com.qrcode.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class QrcodeDemoApplication extends SpringBootServletInitializer {
	@Override//这个表示使用外部的tomcat容器
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		// 注意这里要指向原先用main方法执行的启动类
		return builder.sources(QrcodeDemoApplication.class);
	}
	public static void main(String[] args) {
		SpringApplication.run(QrcodeDemoApplication.class, args);
	}
}


Open the URL after startup is complete

 

 

 A very simple demo

Pay attention to the blogger, the next article is more exciting

One-click three-in-one! ! !

One-click three-in-one! ! !

One-click three-in-one! ! !
Thanks for the one-click triple! ! !

Guess you like

Origin blog.csdn.net/m0_56073435/article/details/131827945