0
点赞
收藏
分享

微信扫一扫

springboot 生成二维码

西街小学的王 2022-05-02 阅读 181

文章目录


前言

如何使用springboot 生成二维码呢?


提示:以下是本篇文章正文内容,下面案例可供参考

一、导入依赖

<!--        生成二维码用-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

二、编写配置文件

主要看fie的配置 一会儿会用到

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/imooc_mall?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher   #to use old Swagger
  redis:
    host: localhost
    port: 6379
    password:
  main:
    allow-circular-references: true    # to use PageHelper : allow circular-references
server:
  port: 8084
mybatis:
  mapper-locations: classpath:mappers/*.xml  #where mybatis.xml is

file:
  upload:
    dir: E:/mall/file/
    ip: 127.0.0.1
    dir: /root/data/code_img/
    ip: xxxxxxx

三、编写代码实现

1 serviceImpl层编写

controller层只需要传来一个string类型的数据就行
这里不写代码了

package com.example.sky.util;

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 java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * 描述:     生成二维码工具
 */
public class QRCodeGenerator {


    public static void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {
        //声明二维码写出者
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

//    public static void main(String[] args) {
//        try {
//            generateQRCodeImage("Hello World", 350, 350, "/Users/didi/Desktop/IdeaProjects/imooc-mall-prepare-static/QRTest.png");
//        } catch (WriterException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}

@Override
    public String qrcode(String orderNo) {
		 @Value("${file.upload.ip}")
    	String ip;
			
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String address = ip + ":" + request.getLocalPort();
        //生成支付url
        String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
        try {
            QRCodeGenerator
                    .generateQRCodeImage(payUrl, 350, 350,
                            Constant.FILE_UPLOAD_DIR + orderNo + ".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //前端访问这个地址会被mvc重定向 从而访问到系统内部的文件
        String pngAddress = "http://" + address + "/images/" + orderNo + ".png";
        return pngAddress;
    }

2 Constant编写

参考结构
在这里插入图片描述

public static String FILE_UPLOAD_DIR;

    @Value("${file.upload.dir}")
    public void setFileUploadDir(String fileUploadDir) {
        FILE_UPLOAD_DIR = fileUploadDir;
    }

3 映射规则编写(出于安全考虑不直接暴露内部路径)

参考结构
在这里插入图片描述

package com.imooc.mall.config;

import com.imooc.mall.common.Constant;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 描述:     配置地址映射
 */
@Configuration
public class ImoocMallWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + Constant.FILE_UPLOAD_DIR);
    }
}

4 测试

我们访问return的url 成功访问到本地的二维码文件

举报

相关推荐

0 条评论