springboot 生成二维码

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

如何使用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 controller层编写

没有service层
controller直接实现了

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

		package com.example.erweimademo.controller;

import com.example.erweimademo.Constant;
import com.example.erweimademo.utils.QRCodeGenerator;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
public class testController {
    @Value("${file.upload.ip}")
    String ip;


    @RequestMapping("/test")
    public  String test(@RequestParam String data){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String address = ip + ":" + request.getLocalPort();


        try {
            QRCodeGenerator
                    .generateQRCodeImage(data, 350, 350,
                            Constant.FILE_UPLOAD_DIR + data + ".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //前端访问这个地址会被mvc重定向 从而访问到系统内部的文件
        String pngAddress = "http://" + address + "/images/" + data + ".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 成功访问到本地的二维码文件
在这里插入图片描述


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qwecxzz

鸡腿

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值