您的位置:首页 > 编程语言 > Java开发

Java生成验证码并进行验证

2017-11-22 15:31 302 查看


一、实现思路

使用BufferedImage用于在内存中存储生成的验证码图片
使用Graphics来进行验证码图片的绘制,并将绘制在图片上的验证码存放到session中用于后续验证
最后通过ImageIO将生成的图片进行输出
通过页面提交的验证码和存放在session中的验证码对比来进行校验


二、生成验证码

页面通过访问servlet来生成验证码,servlet中的代码如下:
package org.test;

import java.awt.Color;
import java.awt.Graphics;
import jav
4000
a.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author worm0527
* 2016-03-22 23:15:54
* 生成验证码
*/
public class ImageServlet extends HttpServlet{
// 图片高度
private static final int IMG_HEIGHT = 100;
// 图片宽度
private static final int IMG_WIDTH = 30;
// 验证码长度
private static final int CODE_LEN = 4;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 用于绘制图片,设置图片的长宽和图片类型(RGB)
BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
// 获取绘图工具
Graphics graphics = bi.getGraphics();
graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
graphics.fillRect(0, 0, 100, 30); // 填充矩形区域

// 验证码中所使用到的字符
char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
String captcha = ""; // 存放生成的验证码
Random random = new Random();
for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
int index = random.nextInt(codeChar.length);
// 随机生成验证码颜色
graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
// 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
captcha += codeChar[index];
}
// 将生成的验证码code放入sessoin中
req.getSession().setAttribute("code", captcha);
// 通过ImageIO将图片输出
ImageIO.write(bi, "JPG", resp.getOutputStream());
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62


三、校验验证码

通过前台提交的验证码与session中数据进行对比来校验验证码,代码如下:
package org.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckCodeServlet extends HttpServlet{

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 获取存放在session中的验证码
String code = (String) req.getSession().getAttribute("code");
// 获取页面提交的验证码
String inputCode = req.getParameter("code");
if(code.toLowerCase().equals(inputCode.toLowerCase())) { // 验证码不区分大小写
// 验证成功,跳转到成功页面
req.getRequestDispatcher("/success.jsp").forward(req, resp);
} else { // 验证失败
req.getRequestDispatcher("/fail.jsp").forward(req, resp);
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

验证码提交页面html代码:
<form action="<%=request.getContextPath() %>/checkCode" method="post">
请输入验证码:<input type="text" name="code">
<input type="submit" value="确定">
</form>
<img alt="验证码" id="scode" src="<%=request.getContextPath() %>/getCode" >
<a href="#" onclick="javascript:flushCode();">看不清?</a>
1
2
3
4
5
6

当生成的验证码不清楚时需要刷新重新生成验证码,js代码如下:
function flushCode() {
// 每次刷新的时候获取当前时间,防止浏览器缓存刷新失败
var time = new Date();
document.getElementById("scode").src = "<%=request.getContextPath()%>/getCode?time=" + time;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: