验证码
1. 本质:图片
2. 目的:防止恶意表单注册
案例说明
1、绘制一个矩形,然后在矩形上面随机生成4个字符,然后在矩形上随机生成5条以上的先。
2、点击图片或者图片旁边的的字符都会刷新图片
RespnseDemo05.java
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;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/ResponseDemo05")
public class RespnseDemo05 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//resp.setContentType("text/http;charset=utf-8");
int width = 100;
int height = 50;
//第一步、在内存中创建一个图片对象
BufferedImage buffIMG = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//第二步、美化图片
//其实写程序画图就和实际画图一样,先选择工具比如画笔,然后选择该工具属性,比如红色
//2 先用画笔工具画一个矩形
Graphics graphics = buffIMG.getGraphics();//获取一个画笔工具
//graphics.drawImage()该方法时画一条线
//2.1 选择画笔颜色
graphics.setColor(Color.white);
//2.2 使用画笔进行填充
//参数说明:1、2-》相对图片的圆点位置,圆点是图片左上角;3、4-》绘制区域大小
graphics.fillRect(0,0,width,height);
//2.3 画外框
graphics.setColor(Color.green);//选颜色
graphics.drawRect(0,0,width-1,height-1);//画一个矩形外框,由于本身外框有默认一个像素大小,因此绘制高度、宽度要减少1像素
//2.4 给图片写上文字
Random rand = new Random();
String strs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(int i=1;i<=4;i++){
//先获取一个索引
int pt = rand.nextInt(strs.length());
char c = strs.charAt(pt);
graphics.drawString(c+"",(width/5)*i,height/2);
}
//2.5 给图片写文字
for (int i = 0; i < 5+rand.nextInt(15); i++) {
int x1 = rand.nextInt(width);
int x2 = rand.nextInt(width);
int y1 = rand.nextInt(height);
int y2 = rand.nextInt(height);
graphics.setColor(new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255)));
graphics.drawLine(x1,y1,x2,y2);
}
//第三步、将图片输出到网页展示
//参数:内存中的图片---输出图片后缀名---输出到哪里去
ImageIO.write(buffIMG,"jpg",resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
windows.onload = function () {
//获取图片对象
var img = document.getElementById("check");
//给图片绑定单击事件
img.onclick = function () {
// 如果给服务发送同样的请求,服务器会让浏览器去找缓冲,因此我们需要发送不同的的请求我们可以通过
//给路径后面?时间戳,事件戳不会永远重复
var time = new Date().getTime();
img.src = "/loginServlet/ResponseDemo05?t="+time;
}
//获取超链接对象
var e_check_next = document.getElementById("check_next");
e_check_next.onclick = function () {
var time = new Date().getTime();
e_check_next.href("/loginServlet/ResponseDemo05?"+time);
}
}
</script>
</head>
<body>
<img id="check" src="/loginServlet/ResponseDemo05" >
<a id="check_next" href="">看不清,换一张?</a>
</body>
</html>
输出: