JSP 前端注册登录界面的图片验证码

个人感觉挺简单的 一开始我也感觉难慢慢一步一步走下来发现巨简单

你们应该都能看懂 看不懂的直接复制到servlet里 直接跑就行 这个代码我也是整理半天的 都有注释

		request.setCharacterEncoding("utf-8");

		BufferedImage bfi = new BufferedImage(80, 25, BufferedImage.TYPE_INT_RGB);
		Graphics g = bfi.getGraphics();
		g.fillRect(0, 0, 80, 25);

		// 验证码字符范围
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
		Random r = new Random();
		int index;
		StringBuffer sb = new StringBuffer(); // 保存字符串
		for (int i = 0; i < 4; i++) {
    
    
			index = r.nextInt(ch.length);
			g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			Font font = new Font("宋体", 30, 20);
			g.setFont(font);
			g.drawString(ch[index] + "", (i * 20) + 2, 23);
			sb.append(ch[index]);
		}

		// 添加噪点
		int area = (int) (0.02 * 80 * 25);
		for (int i = 0; i < area; ++i) {
    
    
			int x = (int) (Math.random() * 80);
			int y = (int) (Math.random() * 25);
			bfi.setRGB(x, y, (int) (Math.random() * 255));
		}

		// 设置验证码中的干扰线
		for (int i = 0; i < 6; i++) {
    
    
			// 随机获取干扰线的起点和终点
			int xstart = (int) (Math.random() * 80);
			int ystart = (int) (Math.random() * 25);
			int xend = (int) (Math.random() * 80);
			int yend = (int) (Math.random() * 25);
			g.drawLine(xstart, ystart, xend, yend);
		}
		HttpSession session = request.getSession(); // 保存到session
		session.setAttribute("verificationCode", sb.toString());
		ImageIO.write(bfi, "JPG", response.getOutputStream()); // 写到输出流
		yanzhengma = (String) session.getAttribute("verificationCode");
		System.err.println(yanzhengma);

很多人会疑惑 我用后端传给前端不能直接输入! 其实你想负责了无需输出 img的 src里面支持直接路径操作 tip6是显示一些后端的处理状态

<img src="${pageContext.request.contextPath}/ValidateCodeUtils" id="image" /> <span id="tip6"></span>

我在网上搜过很多demo 都说的五花八门 一会数字类型一会字母类型 对于初学者来说重要的是实现他之后的自己理解,而不是一堆代码让初学者完全不知从何入手!如果还不懂的QQ 2773938492 1v1讲解 不收费

推广一下个人网站 www.aolanghs.com 首页的是程序员开发必备的资源框架导航 菜单栏顶部是 我对软件+网站的开发经验和一些看法!

猜你喜欢

转载自blog.csdn.net/weixin_44907128/article/details/105876435
今日推荐