01-随机字符验证码

页面 demo (jsp 生成):

image-20200617101032615

Java 代码 生成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 给定字符串随机获取4个字符,并使用StringBuilder拼接成字符串【验证码】
*/
public class GenerateCode {
public static String identifyingCode() {
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
while (sb.length() < 4) {
int index = (new java.util.Random()).nextInt(s.length());//0~s.length()-1
// 处理重复字符:每个新的随机字符在 sb 中使用indexOf()查找下标值,-1为没找到,即不重复
Character ch = new Character(s.charAt(index));
if (sb.indexOf(ch.toString()) < 0) {
sb.append(ch);
}
}
return sb.toString();
}
}

JSP 页面 生成:

1
2
3
4
5
6
// 刷新验证码
function refreshCode() {
console.log("refreshCode");
// 因浏览器的缓存技术,故需欺骗浏览器,每次点击是一次新的图片生成
$("#validateCode").attr("src", "${pageContext.request.contextPath}/../validateCode.jsp?" + Math.random());
}
1
2
3
4
5
6
7
8
9
<!-- 验证码图片 -->
<!-- style="cursor:pointer" 验证码图片鼠标变手型 -->
验证码:<input type="text" name="validateCode">
<img
src="${pageContext.request.contextPath}/validateCode.jsp"
id="validateCode"
style="cursor:pointer"
onclick="refreshCode()"
>

validateCode.jsp - 生成验证码

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Random"%>
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.ImageIO"%>
<%
int width = 60;
int height = 32;
//创建图片对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//设置背景颜色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
//设置边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// create a random instance to generate the codes
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
//画干扰线
for (int i = 0; i < 50; i++) {
int x = rdm.nextInt(width);
int y = rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
//生成四位随机验证码
String capstr = hash1.substring(0, 4);
session.setAttribute("key", capstr);
System.out.println(capstr);
g.setColor(new Color(0, 100, 0));
g.setFont(new Font("Candara", Font.BOLD, 24));
g.drawString(capstr, 8, 24);
g.dispose();
response.setContentType("image/jpeg");
out.clear();
out = pageContext.pushBody();
OutputStream strm = response.getOutputStream();
ImageIO.write(image, "jpeg", strm);
strm.close();
%>

01-随机字符验证码
https://janycode.github.io/2017/06/28/04_网页技术/10_验证码技术/01-随机字符验证码/
作者
Jerry(姜源)
发布于
2017年6月28日
许可协议