验证码图片生成及点击重载功能实现

我是一个从汽车行业转行IT的项目经理,我是Edward,如想了解更多,请关注我的公众号【转行项目经理的逆袭之路】。今天让我们来看看如何用java实现验证码图片生成,以及点击重载的功能。

验证码图片的生成:

1、构造静态字符串,用于随机生成验证码,用StringBuilder就OK了
2、用到了java自带的awt包,使用画布画笔以及各种随机颜色将随机生成的code画上去,同时随机画上干扰线。
3、用ImageIO将图像写出到字节流里,用byte数组获取数据通过socket的输出流直接写到页面上。

package com.webserver.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

public class CreateRandomImageServlet extends HttpServlet{
	//构造静态字符串,用于随机生成验证码
	private static String content;
	private static String code;
	
	static {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 26; i++) {
			sb.append((char)('a'+i));
			sb.append((char)('A'+i));
		}
		
		for (int i = 0; i < 10; i++) {
			sb.append(i);
		}
		content = sb.toString();
	}
	
	
	
	@Override
	public void service(HttpRequest request, HttpResponse response) {
		//画布
		BufferedImage image = new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB);
		//画笔
		Graphics g = image.getGraphics();
		//定义背景颜色
		Color bgColor = new Color(200, 200, 255);
		//画笔蘸色
		g.setColor(bgColor);
		//填充画布
		g.fillRect(0, 0, 70, 30);
		
		//随机生成字符并画上
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			int d= random.nextInt(content.length());
			Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
			g.setColor(color);
			g.setFont(new Font("微软雅黑", Font.BOLD, 20));
			char c = content.charAt(d);
			g.drawString(c+"",i*15+5 , 18);
			sb.append(c);
		}
		code = sb.toString();
		System.out.println("code:"+code);
		
		//随机生成干扰线并画上
		for (int i = 0; i < 5; i++) {
			Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
			g.setColor(color);
			//线的起始终止坐标
			g.drawLine(random.nextInt(71),random.nextInt(31) ,random.nextInt(71), random.nextInt(31));
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpg", out);
			byte[]data=out.toByteArray();
			
			response.setData(data);   //CH结合ServerContext分析需求,就直接out.write()写给你
			response.putHeader("Content-Type", "image/jpeg");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	public static String getCode() {
		return code;
	}

}

点击重载

验证码是有了,可是有时候不太清楚,想换一张怎么办? 有个可以只刷新验证码图片的方法,即给图片加上onclick的JS函数。图片地址不变,页面不加载怎么办? 加个Math.random就搞定!

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Login</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<link rel="stylesheet" type="text/css" href="../bootstrap3/css/bootstrap.css">
		<link rel="stylesheet" type="text/css" href="../bootstrap3/font-awesome-4.7.0/css/font-awesome.css" />
		<style type="text/css">
			body>div {
				margin-top: 50px;
			}
			h1{
				text-align: center;
			}
		</style>
	</head>
	<body>
			<h1>Welcome Back~</h1>
		<div class="container">
			<form action="./login" method="get" class="form-horizontal">
				<div class="form-group">
					<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
					<div class="col-sm-10">
						<input type="email" name="username" class="form-control" id="inputEmail3" placeholder="Email">
					</div>
				</div>
				<div class="form-group">
					<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
					<div class="col-sm-10">
						<input type="password" name="password" class="form-control" id="inputPassword3" placeholder="Password">
					</div>
				</div>
				<div class="form-group">
					<label for="inputPassword3" class="col-sm-2 control-label"><img onclick="changeCode()" id="img" src="./createRandomImage" ></label>
					<div class="col-sm-10">
						<input type="text" name="code" class="form-control" id="inputPassword3" placeholder="VerificationCode">
					</div>
				</div>
				<div class="col-sm-offset-2 col-sm-10">
					<input type="submit" id="" name="" class="btn btn-default" value="Login"/>
				</div>
			</form>
		</div>

		</div>
	</body>
	<script type="text/javascript" src="../bootstrap3/jquery.min.js"></script>
	<script type="text/javascript" src="../bootstrap3/js/bootstrap.js"></script>
	<script type="text/javascript" src="../bootstrap3/js/holder.js"></script>
	<script type="text/javascript" src="../bootstrap3/js/html5shiv.min.js"></script>
	<script type="text/javascript" src="../bootstrap3/js/css3-mediaqueries.js"></script>
	<script type="text/javascript" src="../bootstrap3/js/respond.min.js"></script>
	<script type="text/javascript">
		function changeCode(){
			//src里面的问号不能掉   document.getElementById("img")可以简化
			img.src="./createRandomImage?"+Math.random();
		}
	</script>
</html>

注意:src后面的链接要换成你自己的业务端口,我这个端口的业务的逻辑是会写入xml文件,通过静态块反射得到servlet对象再执行业务的。

原创文章 46 获赞 7 访问量 2061

猜你喜欢

转载自blog.csdn.net/EdwardWH/article/details/105923715