1. 在页面配置验证码的信息
<tr>
<td>验证码:</td><td><input type="text" id="code" name="code" style="height: 31px; width: 163px; ">
<img style="height: 22px;" id="codeImg" name="codeImg" alt="点击更换"
title="点击更换" src="" /></td>
</tr>
2.jsp页面中 jquery代码的实现
$(document).ready(function(){
changeCode();
$("#codeImg").bind('click',changeCode);
});
function changeCode(){
$("#codeImg").attr("src","getCode/code.do?time="+getTimeDate());//attr是设置被选元 素的值 on和bind函数差不多,都是事件绑定函数
}
function getTimeDate(){
var time =new Date();
return time.getTime();//改变验证码的间隔时间
}
3.controller/action/servlet中编写验证码生成的代码【以controller为例】
package com.person.controller.tool;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value="/getCode")//页面的访问路径
public class CodeController {
//把得到的验证码放在session中
@RequestMapping("/code")
public void generate(HttpServletRequest request,HttpServletResponse response){
ByteArrayOutputStream output=new ByteArrayOutputStream();//可以捕获内存缓冲区【生成的图片在缓冲区里面】的数据,将数据装换成字节数组 ,输出流的缓冲区的大小会随着数据的不断写入而自动增加 使用toByteArray() toString()获得生成字节数组的数据
String code=getCode(output);
request.getSession().setAttribute("codeImg", code);
try {
ServletOutputStream out=response.getOutputStream();//servlet程序想servletOutputStream或PrintWriter对象中写入数据将被servlet引擎从response中获得
output.writeTo(out);//将byte数组输出流的全部内容写到指定的输出流参数中
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCode(ByteArrayOutputStream output){
//获得验证码的缓存区
BufferedImage bi=new BufferedImage(68,25,BufferedImage.TYPE_INT_RGB);
//得到制图用的类
Graphics g=bi.getGraphics();
//得到图片的背景颜色
Color c=new Color(224,205,18);
g.setColor(c);
g.fillRect(0, 0, 68, 25);//颜色的填充区域
//设定字体
Font f=new Font("宋体",Font.BOLD,25);//字体加粗
g.setFont(f);
Random r=new Random();//设置产生随机数]
//随机产生9条干扰线,试图中的验证码不易被其他的程序探测到
for(int i=0;i<155;i++){
int x=r.nextInt(68);
int y=r.nextInt(22);
int x1=r.nextInt(12);
int y1=r.nextInt(12);
g.drawLine(x, y, x1, y1);
}
//随机数的产生
char[] ch="1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDASZXCVBNM".toCharArray();
//随机产生4个随机数
int len=ch.length;//四个随机数在该范围内产生
StringBuffer sb=new StringBuffer();//目的就是为了下面的字符拼接
for(int i=0;i<4;i++){
int temp=r.nextInt(len);
g.setColor(new Color(r.nextInt(150),r.nextInt(220),r.nextInt(180)));
g.drawString(ch[temp]+"", i*15+3, 18);//得到每个数字的位置
sb.append(ch[temp]);
}
//ImageIO.write(bi, "jpg", response.getOutputStream())//动态的生成图片
//request.getSession().setAttribute();
try {
ImageIO.write(bi, "jpg",output);//动态的生成图片以jpg的形式放在缓冲区里
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}