效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0a179aa9a90fe184b56d83eb8b14938f.png)
java的Servlet部分
* @Description
* @author BeFondOfSunday
* @date 2021/1/28 10:30
*/
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 {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 150;
int height = 50;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.pink);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLUE);
graphics.setFont(new Font("",Font.PLAIN,35));
graphics.drawRect(0, 0, width - 1, height - 1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(str.length());
char c = str.charAt(index);
graphics.drawString(c+"", width/5*(i+1), height*2/3);
}
graphics.setColor(Color.GREEN);
for (int i=0;i<10;i++){
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
ImageIO.write(image, "png", response.getOutputStream());
}
}
HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码</title>
<script>
window.onload=function (){
let img=document.getElementById("checkCode");
img.onclick=function (){
cl();
}
document.getElementById("check").onclick=function (){
cl();
}
function cl(){
let time = new Date().getTime();
img.src="/responseTest/checkCodeServlet?"+time;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/responseTest/checkCodeServlet">
<a id="check">看不清换一张?</a>
</body>
</html>