Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1e7cd2a

Browse files
[add] 验证码生成工具类和常用方法工具类
1 parent 25cf76f commit 1e7cd2a

File tree

4 files changed

+338
-1
lines changed

4 files changed

+338
-1
lines changed

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
10. 计划任务(定时任务)`Scheduled`
1919
11. 第三方接口调用`RestTemplate`
2020
12. 常用配置(见application.properties)
21+
13. 随机验证码生成`VerifyCodeUtils`
2122

2223
### 更多内容,持续更新
2324

@@ -118,5 +119,5 @@ spring.servlet.multipart.max-request-size=10MB
118119

119120
#### More
120121

121-
更多内容,持续更新,感谢`Star`
122+
更多内容,持续更新,感谢支持!
122123

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package demo.web.controller;
2+
3+
import demo.web.utils.VerifyCodeUtils;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.http.HttpHeaders;
6+
import org.springframework.http.MediaType;
7+
import org.springframework.web.bind.annotation.GetMapping;
8+
import org.springframework.web.bind.annotation.RestController;
9+
10+
import javax.imageio.ImageIO;
11+
import javax.servlet.http.HttpServletResponse;
12+
import javax.servlet.http.HttpSession;
13+
import java.awt.image.BufferedImage;
14+
import java.io.IOException;
15+
16+
/**
17+
* parent
18+
* demo.web.controller
19+
* 随机验证码图片
20+
* header相关说明:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers
21+
*
22+
* @author BlueDriver
23+
* @email cpwu@foxmail.com
24+
* @date 2019年04月03日 14:47 Wednesday
25+
*/
26+
@RestController
27+
public class VerifyCodeController {
28+
@Autowired
29+
private VerifyCodeUtils verifyCodeUtils;
30+
/**
31+
* 验证码长度
32+
*/
33+
private int codeLength = 5;
34+
35+
/**
36+
* 生成随机验证码
37+
* http://localhost:8080/random
38+
*/
39+
@GetMapping("/random")
40+
public void randomCode(HttpServletResponse response, HttpSession session) throws IOException {
41+
String code = verifyCodeUtils.getRandomNum(codeLength);
42+
//将code存入session,用于后期校验
43+
session.setAttribute("code", code);
44+
BufferedImage image = verifyCodeUtils.getImage(code);
45+
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
46+
response.setDateHeader(HttpHeaders.EXPIRES, -1L);
47+
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");//http 1.1
48+
response.setHeader(HttpHeaders.PRAGMA, "no-cache");//http 1.0
49+
//将图片写入响应输出流
50+
ImageIO.write(image, "jpg", response.getOutputStream());
51+
}
52+
}
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
package demo.web.utils;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.springframework.stereotype.Service;
5+
import sun.misc.BASE64Encoder;
6+
7+
import javax.servlet.http.HttpServletRequest;
8+
import java.io.UnsupportedEncodingException;
9+
import java.security.MessageDigest;
10+
import java.security.NoSuchAlgorithmException;
11+
import java.text.ParseException;
12+
import java.text.SimpleDateFormat;
13+
import java.util.Calendar;
14+
import java.util.Date;
15+
import java.util.UUID;
16+
17+
18+
/**
19+
* parent
20+
* demo.web.utils
21+
*
22+
* @author BlueDriver
23+
* @email cpwu@foxmail.com
24+
* @date 2019年04月03日 15:09 Wednesday
25+
*/
26+
@Service
27+
@Slf4j
28+
public class CommonUtils {
29+
private static MessageDigest md5 = null;
30+
private static final BASE64Encoder base64en = new BASE64Encoder();
31+
32+
static {
33+
try {
34+
md5 = MessageDigest.getInstance("MD5");
35+
} catch (NoSuchAlgorithmException e) {
36+
e.printStackTrace();
37+
log.error("md5 init error", e);
38+
}
39+
}
40+
41+
/**
42+
* md5编码加密
43+
*
44+
* @param sourceString: 需要被加密的文本
45+
* @return 加密后的文本
46+
* @throws UnsupportedEncodingException
47+
*/
48+
public String encodeByMd5(String sourceString) throws UnsupportedEncodingException {
49+
return base64en.encode(md5.digest(sourceString.getBytes("UTF-8")));
50+
}
51+
52+
53+
private static SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
54+
55+
public String getFormatDateTimeNow() {
56+
return sdfFull.format(System.currentTimeMillis());
57+
58+
}
59+
60+
public String getFormatDateTime(Date date) {
61+
return sdfFull.format(date);
62+
}
63+
64+
/**
65+
* 格式化时间戳
66+
*
67+
* @param timeStamp
68+
*/
69+
public String getFormatDateTimeByTimeStamp(long timeStamp) {
70+
return sdfFull.format(timeStamp);
71+
}
72+
73+
private static SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
74+
75+
/**
76+
* <P>将年月日字符串转成Date </p>
77+
*
78+
* @param dateString: 合乎规范的年月日字符串
79+
* @return Date
80+
*/
81+
public Date getDateByDateString(String dateString) {
82+
if (dateString == null) {
83+
return null;
84+
}
85+
Date date;
86+
try {
87+
date = sdfDate.parse(dateString);
88+
} catch (ParseException e) {
89+
date = null;
90+
}
91+
return date;
92+
}
93+
94+
public String getDateStringByDate(Date date) {
95+
if (date == null) {
96+
return null;
97+
}
98+
return sdfDate.format(date);
99+
}
100+
101+
public Long getLongByDate(Date date) {
102+
if (date == null) return null;
103+
return date.getTime();
104+
}
105+
106+
/**
107+
* 生成32位的UUID
108+
* 8-4-4-4-12
109+
*/
110+
public String getUUID() {
111+
return UUID.randomUUID().toString().replace("-", "");
112+
}
113+
114+
/**
115+
* <P>计算两个日期相隔天数 </p>
116+
*
117+
* @param before: 起始日期; then: 目标日期
118+
* @return 整数天
119+
*/
120+
public int getDifferenceDay(Date before, Date then) {
121+
Calendar last_c = Calendar.getInstance();
122+
last_c.setTime(before);
123+
Calendar now_c = Calendar.getInstance();
124+
now_c.setTime(then);
125+
int last_year = last_c.get(Calendar.YEAR);
126+
int now_year = now_c.get(Calendar.YEAR);
127+
if (last_year == now_year) {//the same year
128+
return now_c.get(Calendar.DAY_OF_YEAR) - last_c.get(Calendar.DAY_OF_YEAR);
129+
} else {
130+
//different year
131+
long length = then.getTime() - before.getTime();
132+
return (int) length / (1000 * 3600 * 24);
133+
}
134+
}
135+
136+
/**
137+
* 获取request的IP地址
138+
*
139+
* @param request
140+
* @return IP address
141+
*/
142+
public String getIP(HttpServletRequest request) {
143+
String ip = request.getHeader("X-real-ip");//先从nginx自定义配置获取
144+
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
145+
ip = request.getHeader("x-forwarded-for");
146+
}
147+
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
148+
ip = request.getHeader("Proxy-Client-IP");
149+
}
150+
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
151+
ip = request.getHeader("WL-Proxy-Client-IP");
152+
}
153+
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
154+
ip = request.getRemoteAddr();
155+
}
156+
return ip;
157+
}
158+
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package demo.web.utils;
2+
3+
import org.springframework.stereotype.Service;
4+
5+
import java.awt.*;
6+
import java.awt.image.BufferedImage;
7+
import java.util.Random;
8+
import java.util.concurrent.ThreadLocalRandom;
9+
10+
/**
11+
* parent
12+
* demo.web.utils
13+
* 随机验证码生成工具类
14+
*
15+
* @author BlueDriver
16+
* @email cpwu@foxmail.com
17+
* @date 2019年04月03日 14:39 Wednesday
18+
*/
19+
@Service
20+
public class VerifyCodeUtils {
21+
/**
22+
* 宽度
23+
*/
24+
private static final int WIDTH = 250;
25+
/**
26+
* 高度
27+
*/
28+
private static final int HEIGHT = 100;
29+
30+
/**
31+
* 根据code生成图片
32+
*/
33+
public BufferedImage getImage(String code) {
34+
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
35+
36+
Graphics g = image.getGraphics();
37+
38+
drawBackground(g, Color.WHITE);
39+
40+
drawBorder(g, Color.BLUE);
41+
42+
drawRandomLine(g, code.length() * 4);
43+
44+
drawRandomNumber((Graphics2D) g, code);
45+
46+
return image;
47+
}
48+
49+
/**
50+
* 绘制背景色
51+
*/
52+
private void drawBackground(Graphics g, Color color) {
53+
g.setColor(color);
54+
g.fillRect(0, 0, WIDTH, HEIGHT);
55+
56+
}
57+
58+
/**
59+
* 绘制边框
60+
*/
61+
private void drawBorder(Graphics g, Color color) {
62+
g.setColor(color);
63+
g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
64+
}
65+
66+
/**
67+
* 绘制随机干扰线
68+
*/
69+
private void drawRandomLine(Graphics g, int lineCount) {
70+
Random random = new Random();
71+
for (int i = 1; i <= lineCount; i++) {
72+
g.setColor(getRandomColor());
73+
int x1 = random.nextInt(WIDTH);
74+
int y1 = random.nextInt(HEIGHT);
75+
int x2 = random.nextInt(WIDTH);
76+
int y2 = random.nextInt(HEIGHT);
77+
g.drawLine(x1, y1, x2, y2);
78+
}
79+
}
80+
81+
/**
82+
* 绘制随机数
83+
*/
84+
private void drawRandomNumber(Graphics2D g, String code) {
85+
// chinese [\u4e00-\u9f5a]
86+
g.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, HEIGHT / 4 * 3));// linux: fc -list; win7: cmd
87+
// fonts
88+
int x = HEIGHT / 8;
89+
int y = HEIGHT / 2 + HEIGHT / 4;
90+
char[] num = code.toCharArray();
91+
for (char c : num) {
92+
g.setColor(getRandomColor());
93+
int d = new Random().nextInt() % 30;
94+
g.rotate(d * Math.PI / 180, x, y);
95+
g.drawString(c + "", x, y);
96+
g.rotate(-d * Math.PI / 180, x, y);
97+
x += WIDTH / (code.length() + 1);
98+
}
99+
}
100+
101+
/**
102+
* 随机色
103+
*/
104+
public Color getRandomColor() {
105+
return new Color(getRandomInt(255), getRandomInt(255), getRandomInt(255));
106+
}
107+
108+
/**
109+
* 获取指定长度的随机整数
110+
*/
111+
public String getRandomNum(int length) {
112+
StringBuffer sb = new StringBuffer();
113+
for (int i = 0; i < length; i++) {
114+
sb.append(getRandomInt(10));
115+
}
116+
return sb.toString();
117+
}
118+
119+
/**
120+
* 获得指定范围内的随机整数,左开右闭[)
121+
*/
122+
public int getRandomInt(int bound) {
123+
ThreadLocalRandom random = ThreadLocalRandom.current();
124+
return random.nextInt(bound);
125+
}
126+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /