1.servlet代码
/**
* 随机生成验证码
* 1.获取Image对象
* 2.1填充背景色 2.2画边框 生成随机角标 2.3写验证吗 2.4 画干扰线
*3.将图片输出到页面
*/
package cn.itcast.web.servlet;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 随机生成验证码
* 1.获取Image对象
* 2.1填充背景色 2.2画边框 生成随机角标 2.3写验证吗 2.4 画干扰线
*3.将图片输出到页面
*/
int width = 100;
int heigth = 50;
//1.在内存中创建对象
BufferedImage image = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB);
//2.美化图片
//2.1 填充背景色
Graphics g = image.getGraphics();//画笔对象
g.setColor(Color.PINK);
g.fillRect(0,0,width,heigth);
//2.2画边框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,heigth-1);
//生成随机角标
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
Random r = new Random();
for (int i = 1; i <= 4; i++) {
//获取字符位置
int index = r.nextInt(str.length());
//获取字符
char ch = str.charAt(index);
g.drawString(ch+"",width/5*i, heigth / 2);
}
//生成干扰线
for (int i = 0; i < 5; i++) {
int x1 = r.nextInt(width);
int x2 = r.nextInt(width);
int y1 = r.nextInt(heigth);
int y2 = r.nextInt(heigth);
g.drawLine(x1,x2,y1,y2);
}
//将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
效果
在前端展示验证码切换
2.HTML代码
分析:
点击超链接或者图片,需要换一张
1.给超链接和图片绑定单击事件
2.重新设置图片的src属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>切换验证码</title>
<script>
/*
分析:
点击超链接或者图片,需要换一张
1.给超链接和图片绑定单击事件
2.重新设置图片的src属性值
*/
window.onload = function (){
var img = window.document.getElementById("checkcode");
img.onclick = function () {
var date = new Date().getTime();
img.src = "/day14/CheckCodeServlet?" + date;
}
}
</script>
</head>
<body>
<img id="checkcode" src="/day14/CheckCodeServlet">
<a id="change" href="#">看不清换一张?</a>
</body>
</html>
点击图片切换验证码