Servlet 验证码 代码编写
package cn.com.zheng.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageFilter;
import java.io.IOException;
import java.util.Random;
@WebServlet("/comple")
public class Comple extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建图片对象
int with = 100;
int height = 50;
BufferedImage image = new BufferedImage(with, height, BufferedImage.TYPE_3BYTE_BGR);
//美化图片
//获取画笔工具
Graphics graphics = image.getGraphics();
//获取填充工具,进行填充背景se
//设置画笔颜色
graphics.setColor(Color.pink);
graphics.fillRect(0, 0, with, height);
//画边框
graphics.setColor(Color.blue);
graphics.drawRect(0,0,with-1,height-1);
String s="abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
//获取随机数对象
Random random=new Random();
//生成验证ma
graphics.setColor(Color.black);
for (int X= 1; X<=4; X++) {
int i = random.nextInt(s.length());
char c = s.charAt(i);
graphics.drawString(c+"",with/5*X,height/2);
}
//设置干扰线
graphics.setColor(Color.orange);
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(with);
int x2 = random.nextInt(with);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//输出图片
ImageIO.write(image, "png", resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}