public class CaptchaServlet extends HttpServlet {
private static int width = 80;
private static int height = 28;
private static int captchaCharLength = 4;
private static char[] captchaChars = "ABCEHKN23456789PRSTXYZ".toCharArray();
private static int captchaCharsSize = captchaChars.length;
private static final String CAPTCHA_KEY = "_CAPTCHA_SESSION_KEY_";
private static final long serialVersionUID = 5438961220479548231L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
String captchaText = generateRandomCode();
BufferedImage image = generateImage(captchaText);
HttpSession session = request.getSession();
session.setAttribute(CAPTCHA_KEY, captchaText);
try (OutputStream out = response.getOutputStream()) {
ImageIO.write(image, "jpg", out);
}
}
* 生成随机码字符串
*/
private String generateRandomCode() {
Random random = ThreadLocalRandom.current();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < captchaCharLength; i++) {
builder.append(captchaChars[random.nextInt(captchaCharsSize)]);
}
return builder.toString();
}
* 生成验证码图片
*
* @param captchaText
* 验证码字符串
* @return BufferedImage
*/
private BufferedImage generateImage(String captchaText) {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.GRAY);
graphics.drawRect(0, 0, width - 1, height - 1);
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Calibri", Font.BOLD, height - 6));
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int length = captchaText.length();
char[] chars = captchaText.toCharArray();
for (int i = 0; i < length; i++) {
graphics.drawChars(chars, i, 1, ((width - 8) / length) * i + 7,
height / 2 + length / 2 + 6);
}
graphics.dispose();
return image;
}
}