Java生成验证码
Java生成验证码的流程是:
收到请求->生成验证码所用的随机数->使用随机数写出图片->将随机数记录到Session中->输出验证码
Java验证验证码的流程是:
收到请求->获取用户传过来的验证码数字->验证是否正确->输出验证结果
下面通过一个例子来展示验证码的生成流程,该例子使用基本JavaSpring框架的Rest接口,可以使用任何平台来获取验证码:
服务器处理验证码的例子:
1.接收验证码请求:
/**
*接收验证码请求
*/
@RequestMapping(value="captchacode")
publicvoidCaptchaCode(){
try{
CaptchaCodeModelcaptchaCodeModel=newCaptchaCode().getCode();
//将验证码放到Session中
HttpServletRequesthttpServletRequest=super.getRequest();
httpServletRequest.getSession().setAttribute("captchacodekey",captchaCodeModel.getCaptchaCode());
//将图片写到客户端
HttpServletResponsehttpServletResponse=super.getResponse();
//禁止缓存
httpServletResponse.setHeader("Pragma","no-cache");
httpServletResponse.setHeader("Cache-Control","no-cache");
httpServletResponse.setDateHeader("Expires",0);
ServletOutputStreamservletOutputStream=httpServletResponse.getOutputStream();
//输出图片
ImageIO.write(captchaCodeModel.getCaptchaImage(),"jpeg",servletOutputStream);
servletOutputStream.close();
}catch(Exceptione){
logger.info("验证码生成失败:"+e.getMessage());
}
}
2.生成验证码并生成图片:
publicclassCaptchaCode{
privateintwidth=90;//定义图片的width
privateintheight=20;//定义图片的height
privateintcodeCount=4;//定义图片上显示验证码的个数
privateintxx=15;
privateintfontHeight=18;
privateintcodeY=16;
char[]codeSequence={'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W',
'X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
publicCaptchaCodeModelgetCode()throwsIOException{
//定义图像buffer
BufferedImagebuffImg=newBufferedImage(width,height,
BufferedImage.TYPE_INT_RGB);
Graphicsgd=buffImg.getGraphics();
//创建一个随机数生成器类
Randomrandom=newRandom();
//将图像填充为白色
gd.setColor(Color.WHITE);
gd.fillRect(0,0,width,height);
//创建字体,字体的大小应该根据图片的高度来定。
Fontfont=newFont("Fixedsys",Font.BOLD,fontHeight);
//设置字体。
gd.setFont(font);
//画边框。
gd.setColor(Color.BLACK);
gd.drawRect(0,0,width-1,height-1);
//随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。
gd.setColor(Color.BLACK);
for(inti=0;i<40;i++){
intx=random.nextInt(width);
inty=random.nextInt(height);
intxl=random.nextInt(12);
intyl=random.nextInt(12);
gd.drawLine(x,y,x+xl,y+yl);
}
//randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
StringBufferrandomCode=newStringBuffer();
intred=0,green=0,blue=0;
//随机产生codeCount数字的验证码。
for(inti=0;i<codeCount;i++){
//得到随机产生的验证码数字。
Stringcode=String.valueOf(codeSequence[random.nextInt(36)]);
//产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
red=random.nextInt(255);
green=random.nextInt(255);
blue=random.nextInt(255);
//用随机产生的颜色将验证码绘制到图像中。
gd.setColor(newColor(red,green,blue));
gd.drawString(code,(i+1)*xx,codeY);
//将产生的四个随机数组合在一起。
randomCode.append(code);
}
CaptchaCodeModelcaptchaCodeModel=newCaptchaCodeModel();
captchaCodeModel.setCaptchaCode(randomCode.toString());
captchaCodeModel.setCaptchaImage(buffImg);
returncaptchaCodeModel;
}
publicclassCaptchaCodeModel{
//验证码的String形式
privateStringcaptchaCode;
//验证码的图片形式
privateBufferedImagecaptchaImage;
publicStringgetCaptchaCode(){
returncaptchaCode;
}
publicvoidsetCaptchaCode(StringcaptchaCode){
this.captchaCode=captchaCode;
}
publicBufferedImagegetCaptchaImage(){
returncaptchaImage;
}
publicvoidsetCaptchaImage(BufferedImagecaptchaImage){
this.captchaImage=captchaImage;
}
}
3.接收用户传过来的验证码并验证:
/**
*验证验证码
*/
@RequestMapping(value="valicatpcha")
publicvoidregister_R(){
PageDatapageData=super.getPageData();
//获取验证码
StringcaptchaCode=pageData.getString("captchacode");
HttpServletRequesthttpServletRequest=super.getRequest();
ObjectcodeObject=httpServletRequest.getSession().getAttribute(“captchacodekey”);
//验证码错误
if(codeObject==null
||Tools.isEmptyString(captchaCode)
||!String.valueOf(codeObject).toUpperCase()
.equals(captchaCode.toUpperCase())){
setResult(
MessageManager.getInstance().getMessage("invalidcaptcha"),
ResultType.Error);
return;
}
}
页面请求验证码并验证的例子:
functionvalidcaptchacode(captchaCode){
$.ajax({
type:"POST",
url:"valicatpcha",
data:{
captchacode:captchaCode,
tm:newDate().getTime()
},
dataType:"json",
cache:false,
success:function(data){
alert(data);
},
error:function(data){
alert(data);}
});
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!