一、新建Servlet
在doGet方法里写入
//新建一张200*100的RGB图片,默认为黑色
BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
//以图片为背景创建画板
Graphics2D graphics = image.createGraphics();
//为画板设置画笔,设置白色
graphics.setColor(Color.WHITE);
//为画板填充颜色,即把整个黑色涂成白色
graphics.fillRect(0, 0, 200, 100);
//输出字节流
ServletOutputStream os = response.getOutputStream();
//输出图片
ImageIO.write(image, "jpg", os);
输出在浏览器,蓝色是我选中以标识由图片显示。
二、画出数字
//设置字体
graphics.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 30));
//创建画笔,用数组存储多个画笔
Color[] colors = new Color[]{
Color.BLACK,Color.BLUE,Color.RED,Color.GRAY
};
//添加4个数字
int[] numarr = new int[4];
//设置0-9随机数字
Random rand = new Random();
//将数字显示出来
for(int i=0;i<4;i++) {
graphics.setColor(colors[rand.nextInt(colors.length)]);
numarr[i]=rand.nextInt(10);
graphics.drawString(String.valueOf(numarr[i]), i*50, 70+rand.nextInt(21)-10);
}
drawString方法为画板添加字符串,第一个参数str表示要画的字符串,第二个参数表示横坐标起点,第三个参数表示纵坐标起点,注意纵坐标是从下开始画的。
三、设置横切线
//设置字体
graphics.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 30));
//创建画笔,用数组存储多个画笔
Color[] colors = new Color[]{
Color.BLACK,Color.BLUE,Color.RED,Color.GRAY
};
//添加4个数字
int[] numarr = new int[4];
//设置随机数字
Random rand = new Random();
//将数字显示出来
for(int i=0;i<4;i++) {
graphics.setColor(colors[rand.nextInt(colors.length)]); //随机设置画笔的颜色
numarr[i]=rand.nextInt(10); //设置0-9的随机数字
graphics.drawString(String.valueOf(numarr[i]), i*50, 70+rand.nextInt(21)-10); //随i动态变化横坐标的位置,以及纵坐标在60-70浮动
graphics.drawLine(0, rand.nextInt(100), 200, rand.nextInt(100)); //设置横切线防止识别
}
drawLine为画板添加直线,第一个参数x1表示横坐标起点,第二个参数y1表示纵坐标起点,第三个参数x2表示横坐标终点,第四个y2表示纵坐标终点。
四、刷新验证码
在jsp或是html通过servlet的映射地址传照片过来。
<img src="validCode" width="100" height="50"/>
设置超链接刷新验证码,用jQuery控制img的src不断变化,因为如果页面不跳转的话,浏览器有缓存功能,不把请求地址动态变化的话,是不会再次请求地址的。所以传入一个date参数表示当前的时间,不断改变src的值,就能不跳转页面的情况下再次请求地址返回不一样的数据。return false表示点击超链接时不跳转。
<a href="#">看不清</a>
<script>
$(function(){
$("a").on("click",function(){
$("img").attr("src","validCode?date="+new Date());
return false;
})
})
</script>