java 验证码实例
时间: 2023-03-03 12:35:56 浏览: 88
以下是一个使用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.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 120;
private static final int HEIGHT = 40;
private static final int LENGTH = 4;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuffer sRand = new StringBuffer();
for (int i = 0; i < LENGTH; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
request.getSession().setAttribute("captcha", sRand.toString());
g.dispose();
ImageIO.write(image, "JPEG", out);
out.close();
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
```
这个Servlet会在请求时生成一个验证码并将其写入一个JPEG图像中,然后将该图像发送回浏览器。要验证用户输入的验证码,只需检查该值是否与上一个请求中存储在会话中的验证码相同即可。
阅读全文