javaweb:如何改进上次二维码例子?

思考题:如何改进上次二维码例子?

1、创建codeLogin.jsp
在这里插入图片描述

第二步:修改codeLogin.jsp内容,只需要替换body内容既可

<body>
	<form action="/javaweb05/Login" method="post">
		用户:<input type="text" placeholder="请输入账号" name="no"/><br>
		密码:<input type="text" placeholder="请输入密码" name="pass"/><br>
		<input type="submit" value="提交">
	</form>
</body>

第三步:创建servlet,名字是Login
在这里插入图片描述

第四步:修改Login的doGet方法

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取参数
		String no = request.getParameter("no");
		String pass = request.getParameter("pass");
		
		// 设置Cookie
		request.getSession().setAttribute("no", no);
		
		// 跳转页面
		response.sendRedirect(request.getContextPath() + "/welcome.jsp");
	}

第五步:创建welcome.jsp
在这里插入图片描述

第六步:编写welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="10">
<title>Insert title here</title>
</head>
<body>
<%
	String no = session.getAttribute("no").toString();
	Date date=new Date();
	String time=date.toLocaleString();
%>
<img alt="" src="/javaweb05/QRCode?no=<%=no%>&t=<%=time%>" >
<div>用户:<%=no%></div>
<div id="lasttime"></div >
<div><%=time %></div >
</body>
	<script type="text/javascript">
		var dom=document.getElementById("lasttime");
		var t=10;
		setInterval(()=>{
			dom.innerHTML='剩余'+t.toString()+'刷新'
			t--;
		},1000);
	</script>
</html>

第七步:编写二维码工具类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nvivA3KD-1618123202135)(C:\Users\16286\AppData\Roaming\Typora\typora-user-images\image-20210411142529874.png)]

第八步:工具类内容详情

很多包找不到,因为我们还没有导入jar包,接下来要导入jar包了

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QrCodeUtils {
	private static final String CHARSET = "UTF-8";
	private static final String FORMAT_NAME = "JPG";

	private static final int QRCODE_SIZE = 300; //二维码尺寸
	private static final int WIDTH = 60; //LOGO宽度

	private static final int HEIGHT = 60;//LOGO高度

	/**
	 * 创建二维码图片
	 *
	 * @param content    内容
	 * @param logoPath   logo
	 * @param isCompress 是否压缩Logo
	 * @return 返回二维码图片
	 * @throws WriterException e
	 * @throws IOException     BufferedImage
	 */
	public static BufferedImage createImage(String content, String logoPath, boolean isCompress)
			throws WriterException, IOException {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
				hints);
		int width = bitMatrix.getWidth();
		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);
			}
		}
		if (logoPath == null || "".equals(logoPath)) {
			return image;
		}

		// 插入图片
		QrCodeUtils.insertImage(image, logoPath, isCompress);
		return image;
	}

	/**
	 * 添加Logo
	 *
	 * @param source     二维码图片
	 * @param logoPath   Logo
	 * @param isCompress 是否压缩Logo
	 * @throws IOException void
	 */
	private static void insertImage(BufferedImage source, String logoPath, boolean isCompress) throws IOException {
		File file = new File(logoPath);
		if (!file.exists()) {
			return;
		}

		Image src = ImageIO.read(new File(logoPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		// 压缩LOGO
		if (isCompress) {
			if (width > WIDTH) {
				width = WIDTH;
			}

			if (height > HEIGHT) {
				height = HEIGHT;
			}

			Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			// 绘制缩小后的图
			g.drawImage(image, 0, 0, null);
			g.dispose();
			src = image;
		}

		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (QRCODE_SIZE - width) / 2;
		int y = (QRCODE_SIZE - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成带Logo的二维码
	 *
	 * @param content    二维码内容
	 * @param logoPath   Logo
	 * @param destPath   二维码输出路径
	 * @param isCompress 是否压缩Logo
	 * @throws Exception void
	 */
	public static void create(String content, String logoPath, String destPath, boolean isCompress) throws Exception {
		BufferedImage image = QrCodeUtils.createImage(content, logoPath, isCompress);
		mkdirs(destPath);
		ImageIO.write(image, FORMAT_NAME, new File(destPath));
	}

	/**
	 * 生成不带Logo的二维码
	 *
	 * @param content  二维码内容
	 * @param destPath 二维码输出路径
	 */
	public static void create(String content, String destPath) throws Exception {
		QrCodeUtils.create(content, null, destPath, false);
	}

	/**
	 * 生成带Logo的二维码,并输出到指定的输出流
	 *
	 * @param content    二维码内容
	 * @param logoPath   Logo
	 * @param output     输出流
	 * @param isCompress 是否压缩Logo
	 */
	public static void create(String content, String logoPath, OutputStream output, boolean isCompress)
			throws Exception {
		BufferedImage image = QrCodeUtils.createImage(content, logoPath, isCompress);
		ImageIO.write(image, FORMAT_NAME, output);
	}

	/**
	 * 生成不带Logo的二维码,并输出到指定的输出流
	 *
	 * @param content 二维码内容
	 * @param output  输出流
	 * @throws Exception void
	 */
	public static void create(String content, OutputStream output) throws Exception {
		QrCodeUtils.create(content, null, output, false);
	}

	/**
	 * 二维码解析
	 *
	 * @param file 二维码
	 * @return 返回解析得到的二维码内容
	 * @throws Exception String
	 */
	public static String parse(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		result = new MultiFormatReader().decode(bitmap, hints);
		return result.getText();
	}

	/**
	 * 二维码解析
	 *
	 * @param path 二维码存储位置
	 * @return 返回解析得到的二维码内容
	 * @throws Exception String
	 */
	public static String parse(String path) throws Exception {
		return QrCodeUtils.parse(new File(path));
	}
    /**
     * 判断路径是否存在,如果不存在则创建
     *
     * @param dir 目录
     */
    public static void mkdirs(String dir) {
        if (dir != null && !"".equals(dir)) {
            File file = new File(dir);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
        }
    }
}

第九步:导入二维码工具类需要的jar包

baidu网盘下载地址

链接:https://pan.baidu.com/s/1okIWcfQPpNOjVlwGrBeXow 
提取码:c2ld 
复制这段内容后打开百度网盘手机App,操作更方便哦--来自百度网盘超级会员V4的分享

下载完之后,把jar包添加到lib文件夹

接下来配置jar包,没配置可能用不了

鼠标右键lib文件夹

找到Build Path

点击Configure Build Path
出现下图画面之后
点击红笔圈起来的按钮

在这里插入图片描述
选择你的项目名、找到lib下的jar包,全部选定之后OK

最后Apply and Close,就导入成功
在这里插入图片描述

第十步:创建二维码生成Servlet

在这里插入图片描述

第十一步:修改QRCode的doGet方法

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String no = request.getParameter("no");
		String t = request.getParameter("t");
		String content = no + "|" + t;
		System.out.println(content);
		ServletOutputStream output = response.getOutputStream();
		try {
			QrCodeUtils.create(content, output);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

第十一步:最后测试
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值