springboot 生成二维码

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

文章目录

  • 前言
  • 一、导入依赖
  • 二、编写配置文件
  • 三、编写代码实现
      • 1 controller层编写
      • 2 Constant编写
      • 3 映射规则编写(出于安全考虑不直接暴露内部路径)
      • 4 测试


前言

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


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

一、导入依赖


        
            com.google.zxing
            javase
            3.3.0
        

二、编写配置文件

主要看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编写

参考结构
springboot 生成二维码_第1张图片

public static String FILE_UPLOAD_DIR;

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

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

参考结构
springboot 生成二维码_第2张图片

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 成功访问到本地的二维码文件
springboot 生成二维码_第3张图片


你可能感兴趣的:(java,spring,boot,java,后端)