以下为在Servlet中实现四位数字验证码的源码分析。
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.awt.*;
/*
* 功能:调用AuthCodeServlet可以生成一个4位数字的验证码图片,验证码的图片宽度和高度可以通过配置文件进行定义
* 验证码调用格式为: /servlet/AuthCodeServlet?w=78&h=32
* 或者使用默认长宽/servlet/AuthCodeServlet
*/
public class AuthCodeServlet extends HttpServlet {
// 处理post
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
doGet(req,res);
}
//设置字体
private Font mFont=new Font("Times New Roman", Font.PLAIN,16);
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
HttpSession session=request.getSession();
response.setContentType("image/gif");
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width=70; //验证码默认长度
int height=24; //验证码默认宽度
if(request.getParameter("w")!=null && !request.getParameter("w").equals(""))
width = Integer.parseInt(request.getParameter("w"));
if(request.getParameter("h")!=null && !request.getParameter("h").equals(""))
height = Integer.parseInt(request.getParameter("h"));
ServletOutputStream out=response.getOutputStream(); //获取输出流
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //新建验证图片,并设置验证码图片的大小
Graphics gra=image.getGraphics(); //获取图形上下文
Random random=new Random();
gra.setColor(getRandColor(260,210)); //设置验证码的图片背景色
gra.fillRect(0,0,width,height);
gra.setColor(Color.BLUE); //设置字体色为蓝色
gra.setFont(mFont); //设置定义的字体格式
// 随机产生254条干扰直线,使图象中的验证码不易被解析程序分析到
gra.setColor(getRandColor(110,240));
for (int i=0;i<254;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(63);
int yl = random.nextInt(64);
gra.drawLine(x,y,x+xl,y+yl);
}
// 取随机产生的验证码(4位数字)
String sRand="";
for (int i=0;i<4;i++){
String rand=String.valueOf(random.nextInt(353));
sRand+=rand;
// 将认证码显示到图象中
gra.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//调用随机函数构建随机颜色三素
gra.drawString(rand,13*i+6,16);
}
session.setAttribute("authCode",sRand);
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
}
static Color getRandColor(int ff,int cc){
//给定范围获得随机颜色
Random random = new Random();
if(fc>255) ff=255;
if(bc>255) cc=255;
int r=ff+random.nextInt(cc-ff);
int g=ff+random.nextInt(cc-ff);
int b=ff+random.nextInt(cc-ff);
return new Color(r,g,b);
}
static public String getAuthCode(HttpSession session){
//返回验证码
return (String)session.getAttribute("AuthCode");
}
}