javaweb生成验证码图片的代码
时间: 2023-07-10 15:33:11 浏览: 110
以下是一个简单的 JavaWeb 生成验证码图片的代码示例:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 80; // 验证码图片的宽度
private static final int HEIGHT = 30; // 验证码图片的高度
private static final int CODE_COUNT = 4; // 验证码字符数
private static final int LINE_COUNT = 20; // 干扰线数
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
// 设置响应头信息,禁止缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 创建图片缓存区
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 设置背景色并绘制矩形框
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.GRAY);
g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
// 生成随机数并将其转换为字符串
Random random = new Random();
String code = "";
for (int i = 0; i < CODE_COUNT; i++) {
int c = random.nextInt(10);
code += c;
}
// 将生成的验证码存入 session 中
HttpSession session = request.getSession();
session.setAttribute("verifyCode", code);
// 绘制干扰线
for (int i = 0; i < LINE_COUNT; i++) {
int x1 = random.nextInt(WIDTH);
int y1 = random.nextInt(HEIGHT);
int x2 = random.nextInt(WIDTH);
int y2 = random.nextInt(HEIGHT);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawLine(x1, y1, x2, y2);
}
// 绘制验证码
Font font = new Font("Arial", Font.BOLD, 20);
g.setFont(font);
for (int i = 0; i < CODE_COUNT; i++) {
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawString(String.valueOf(code.charAt(i)), 20 * i + 6, 25);
}
// 输出图片
try {
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
doGet(request, response);
}
}
```
在 `doGet` 方法中,首先设置响应头信息,禁止缓存,然后创建一个 `BufferedImage` 对象用来存储验证码图片。接着设置背景色并绘制矩形框,生成随机数并将其转换为字符串,将生成的验证码存入 session 中,然后绘制干扰线和验证码。最后将生成的图片通过 `ServletOutputStream` 输出到浏览器中。在 `doPost` 方法中,直接调用 `doGet` 方法。
阅读全文