
package com.servlet02.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 获取随机验证码图像
*
* @author Administrator
*
*/
@WebServlet(value = "/getCodes02")
public class CodesServelt02 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
// 1.创建验证码图像(宽,高,类型)
BufferedImage image = new BufferedImage(160, 50, BufferedImage.TYPE_3BYTE_BGR);
// 2.在该图像上获取画笔
Graphics g = image.getGraphics();
// 设置图像背景色和前景色
g.setColor(Color.WHITE);//设置笔刷白色
g.fillRect(1,1,158,48);//填充整个屏幕 (x,y,w,h)
g.setColor(Color.BLACK); //设置笔刷
// 字体
Font font = new Font("华文琥珀", Font.ITALIC , 24);
g.setFont(font);
// x轴坐标
int x = 20;
for (int i = 1; i <= 6; i++) {
// 3.获取验证码
String code = getCode();
// 4.利用画笔向图像中写随机验证码(验证码,x轴,y轴)
g.drawString(code, x, 30);
x += 20;
}
// 5.释放画笔资源
g.dispose();
// 6. 将图像输出给客户端
ImageIO.write(image, "JPEG", response.getOutputStream());
}
/**
* 获取随机验证码
*
* @return
*/
protected String getCode() {
// 要返回的随机验证码(一位)
String code = "";
// 验证码库
String codes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 验证码库的长度
int len = codes.length();
// 获取随机对象
Random random = new Random();
// 随机验证码
// 获取随机索引
int index = random.nextInt(len);
// 根据索引获取随机字符
char ch = codes.charAt(index);
code = String.valueOf(ch);
return code;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>codes.jsp</title>
</head>
<body>
<img alt="" src="http://localhost:8080/Servlet02/getCodes02">
</body>
</html>