生成山东农大二维码

生成山东农大二维码

<%--
  Created by IntelliJ IDEA.
  User: CaptainDong
  Date: 2023/6/7
  Time: 15:26
  To change this template use File | Settings | File Templates.
--%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    访问百度网址的二维码


请使用移动设备扫描以下二维码

 

package com.dong.erweima;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.zxing.BarcodeFormat;
//import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

@WebServlet("/qrcode")
public class QRCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "http://www.sdau.edu.cn/";
        int size = 250;

        try {
            // 设置二维码参数
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, size, size);

            // 将二维码输出到response流中
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            response.setContentType("image/png");
            ImageIO.write(image, "png", response.getOutputStream());
        } catch (WriterException e) {
            // 发生错误时,返回404 Not Found错误页面
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

运行结果:

生成山东农大二维码_第1张图片

 

你可能感兴趣的:(Javaweb网站练习,Javaweb模块模型,Java知识学习,java,开发语言)