利用Java生成一次性验证码
利用Java生成一次性验证码
标签: Jave Servlet
通过Response想浏览器输出一次性的验证码,首先因为验证码是一次性随机生成的,所以我们不能对验证码进行缓存。首先,我们设置Response相关的控制缓存响应头:
代码:
response.setDateHeader("Expirse",0);
response.setHeader("Content-control","no-cache");
response.setHeader("Pragma","no-cache");
设置完响应头之后我们就要开始写验证码的Servlet了。
首先生成一个验证码有一下几个步骤
- 在内存中生成一张图片;
- 获取图片画布;
- 填充这个画布;
- 为这个画布画上边框;
- 画字;
- 画干扰线等;
- 输出图片;
下来让我们一步一步来实现这个Servlet
1.在内存中生成一张图片
int base=30;
int width=base*4;
int height=base;
//生成随机的方法;
private Random rand=new Random();
private int getRand(int begin,int end){
return rand.getRand(end-begin)+begin;
}
//生成一张图片
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
2.通过Graphics2D类获取图片的画布
Graphics2D g=(Graphics2D)image.getGraphics();
3.为这个画布填充颜色
g.setColor(Color.white);
g.fillRect(0,0,width,height);
4.为这个画布划伤边框
g.setColor(Color.red);
g.drawRect(0,0,width-1,height-1);
5.画字
String strs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(int i=0;i<4;i++){
g.setColor(new Color(getRand(0,255),getRand(0,255),getRand(0,255)));
g.setFont(new Font("微软雅黑","BLOD",20));
double theta=getRand(-45,45)/180*MATH.PI;
g.rotate(theta,x,y);
g.drawString(strs.charAt(getRand(0,strs.length()-1))+"",x,y);
g.rotate(theta,x,y);
}
6.画干扰线等
//画干扰线
for(int i=0,i<4,i++){
g.setColor(getRand(0,255),getRand(0,255),getRand(0,255));
g.drawLine(getRand(0,width), getRand(0,height), getRand(0,width), getRand(0,height));
}
//画干扰圈
for(int i=0;i<5;i++){
g.setColor(new Color(getRand(0,255),getRand(0,255),getRand(0,255)));
int r=getRand(5,15);
g.drawOval(getRand(0,width),getRand(0,width),r,r);
}
7.输出图片
g.dispose();
ImageIO.write(image,"jpg",response.getOutputStream());
以上一个一次性验证码的Servlet就写好了
让我们来验证一下;
首先要写一个ValiImg.jsp来验证这个验证码Servlet:
代码如下:
<%@ 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">
<script tpyt="text/javascript">
function changeOne(obj){
obj.src="/LearnServlet/ValiImgServlet?time="+new Date().getTime();
//随着时间的变化验证码会随之变化;
}
</script>
<title>验证码</title>
</head>
<body>
用户名:<input type="text"/><br>
密码:<input type="password" value="password"/><br>
请输入验证码:<input tpye="text"/><img src="/LearnServlet/ValiImgServlet" onclick="changeOne(this)" style="cursor: pointer;"/><br>
<input type="submit" value="submit"/>
</body>
</html>
好了,通过Graphics类就写好了一个一次性验证码的Servlet,通过Response就可向客户端浏览器进行输出了。

浙公网安备 33010602011771号