java后台生成二维码并在jsp页面显示(初学者)

java后台生成二维码并在jsp页面显示(初学者)

注意:本人用的是:

  • JDK12
  • eclipse
  • tomcat

使用到插件和jar包

  • zxing3.2.1.jar jar包百度或者私我qq:1290792596 欢迎商讨学习
  • jquery-3.4.1.js 这个js哪里都有随便百度一个就行啦

注意这里JDK12方法和JDK1.8有所差距

1.== Encoder encoder = Base64.getEncoder();==
2. byte[] binary = encoder.encode(bytes);

第一种方式生成二维码并显示在前端jsp页面:

首先我们要在jsp页面显示需要建一个web项目,这里我的web项目名字为webd01.

WebCount的创建和展示:

java后台生成二维码并在jsp页面显示(初学者)_第1张图片

src的结构图:

java后台生成二维码并在jsp页面显示(初学者)_第2张图片
我们从前向后写先写web层:
创建one.jsp页面:这里引入easyui/jquery-3.4.1.js ,并用 οnclick="lick()"进行传值

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="easyui/jquery-3.4.1.js"></script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 数据发送到OneSeervlet -->

	<h1>二维码</h1>
	<!-- 生成的二维码图片展示 标签 img -->
	<img  id="img1" alt="##" src="">
	<input id="in1" type="text" name = "text" >
	<input  type="button" onclick="lick()" value="生成二维码">
	

</body>
<script type="text/javascript">

function lick() {
	var r = $("#in1").val();
	if(r != null && r !=""){
		document.getElementById("img1").src="<%=request.getContextPath() %>/OneSeervlet?text="+r+"&"+Math.random();
	}
}

</script>


</html>

创建完jsp配置web.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>webd01</display-name>
  <welcome-file-list>
    <welcome-file>one.jsp</welcome-file>
  </welcome-file-list>
  <!-- OneServlet 的 servlet 配置 -->
  <servlet>
    <description></description>
    <display-name>OneSeervlet</display-name>
    <servlet-name>OneSeervlet</servlet-name>
    <servlet-class>com.zhiyou.servlet.OneSeervlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>OneSeervlet</servlet-name>
    <url-pattern>/OneSeervlet</url-pattern>
  </servlet-mapping>
</web-app>

配置完web.xml,我们写src层面(这里没有用什么框架等等,全部为最基础的Java所写)

这里我们直接用右键创建servlet(右键生成的servlet, web.xml 是不用配置的系统自己生成------>我是这样创建的)
下面是servlet代码:(这里注意我们用到Code encoder = new Code(); 还没有创建所以会报错)

package com.zhiyou.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * One.jsp的 Servlet 
 */
public class OneSeervlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
		protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  String content = request.getParameter("text");
		  System.out.println(content);
		  request.getSession().setAttribute("e", content);
		  
	        Code encoder = new Code();
	       // if (content != null && content !="") {}
	        	 try {
	 				encoder.encoderQRCoder(content, response,request);
	 			} catch (Exception e) {
	 				// TODO Auto-generated catch block
	 				e.printStackTrace();
	 			}
	}

}

在上面的servlet里边我们创建啦Code encoder = new Code();所以现在我们创建 Code.class

package com.zhiyou.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class Code {

	public void encoderQRCoder(String content, HttpServletResponse response,HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		
		int width = 300;
		int height = 300;
		String format = "png";
		String attribute = (String) request.getSession().getAttribute("e");
		String content1 = attribute;
		
		//生成 二维码参数
		HashMap hints = new HashMap();
		//二维码内容编码格式
		hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
		//容错率
		hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
		//生成二维码的边框线宽度
		hints.put(EncodeHintType.MARGIN, 1);
		
		try {
			BitMatrix  bitMatrix =	new MultiFormatWriter().encode(content1, BarcodeFormat.QR_CODE, width, height,hints);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			BufferedImage image = toBufferedImage(bitMatrix);
			//把png格式转换成IO流
			ImageIO.write(image, format, response.getOutputStream());
			byte[] bytes = out.toByteArray();
			//将字节数组转换为二进制
			 Encoder encoder = Base64.getEncoder();
			 //没有去除两边空格.trim()
			 byte[] binary = encoder.encode(bytes);
		} catch (WriterException e) {
			e.printStackTrace();
			System.out.println(e);
		}
		
	}

	private static BufferedImage toBufferedImage(BitMatrix bitMatrix) {
		int width = bitMatrix.getHeight();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
		return image;
	}
	

	

}

代码就这么多已经完啦.
感谢大家阅读我的文章 本人是个初学者有很多地方有漏洞 也希望大家不要要求太高 我来这里的初衷还是学习—>保持学习的态度. 还有祝大家学习愉快 嘿嘿

你可能感兴趣的:(Java,Java开发)