网页登录中图片验证的实现,核心代码如下所示:
创建图片资源 BufferedImage image = new BufferedImage(WIDTH, Hight, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();
* 设置内容
/
private void setContent(Graphics2D g) {
g.setColor(Color.BLACK);
g.setFont(new Font("宋体", Font.BOLD,40));
int x = 20;
int y = 40;
for(int i = 0; i < 4; i ++){
double degree = new Random().nextInt()%30 ;
g.rotate(degree * Math.PI/180, x + 20, y - 20);
String num = new Random().nextInt(9) + "";
g.drawString(num, x, y);
g.rotate(-degree Math.PI/180, x + 20, y - 20);
x += 30;
}
}
/**
* 设置干扰线
* @param g
*/
private void setLine(Graphics g) {
g.setColor(Color.BLACK);
for(int i = 0; i < 5; i ++){
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(Hight);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(Hight);
g.drawLine(x1, y1, x2, y2);
}
}
/**
* 画出边框
* @param g
*/
private void setFrame(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(0, 0, WIDTH, Hight);
}
/**
* 填充背景颜色
* @param g
*/
private void setBackgroundColor(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(1, 1, WIDTH-2, Hight-2);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//将数据写入流中
ImageIO.write(image, "jpg", response.getOutputStream());
在登录中我们有时会使用汉字认证,汉字的范围:\u4e00-\u9fa5。
实现点击图片换一张,在js点击事件中的代码:
this.src = this.src + "?" + new Date().getTime();
this:指的是图片image标签
src:指的是servlet资源,将资源重新赋值给image,就是再次向服务器发送请求.
"?" + new Date().getTime()
:由于缓存的存在,这句话是为了避免和上次发送的请求相同而取本地缓存。