Cheug's Blog

当前位置:网站首页 / JAVA / 正文

Servlet画验证码

2019-05-16 / JAVA / 943 次围观 / 0 次吐槽 /

Servlet

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

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;


@WebServlet("/VerificationCode")
public class VerificationCode2 extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//创建随机数
		Random random = new Random();
		//创建图片内存对象
		int width = 100;
		int height = 30;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//获取图片
		Graphics graphics = image.getGraphics();
		//设置图片背景颜色
		graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));//设置画笔颜色
		graphics.fillRect(0, 0, width, height);
		//加干扰线
		graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
		for(int i=0;i<5;i++) {
			int x1Start = random.nextInt(width);
			int x2Start = random.nextInt(width);
			int y1End = random.nextInt(height);
			int y2End = random.nextInt(height);
			graphics.drawLine(x1Start, y1End, x2Start, y2End);//画线
		}
		//画随机数
		for(int i=1;i<5;i++) {
			graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
			graphics.drawString(random.nextInt(10)+"", 20*i, 20);//画字符 
		}
		//输出图片 设置响应格式
		resp.setContentType("image/jpeg");
		ImageIO.write(image, "jpeg", resp.getOutputStream());
	}
}

包实现 : ValidateCode.jar

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ValidateCode vc = new ValidateCode(150, 50, 4, 15);
		vc.write(resp.getOutputStream());
	}

html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>验证码</title>
<script type="text/javascript">
	function refreshCode() {
		var imgCode = document.getElementById('code');
		imgCode.src = '/web/VerificationCode?' + new date().getTime();
	}
</script>
</head>
<body>
<form action="">
	用户名:<input type="text"><br/>
	密码:<input type="password"><br/>
	验证码:<input type="text"><br/>
	<a href=""><img id="code" src="/web/VerificationCode">刷新验证码</a>
</form>
</body>
</html>


Powered By Cheug's Blog

Copyright Cheug Rights Reserved.