时间工具类、HttpClinet工具类

时间工具类

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
###Java时间格式转换大全

package com.changfu.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
* 时间计算工具类
*/
public class DateUtil {
/**
* the milli second of a day
*/
public static final long DAYMILLI = 24 * 60 * 60 * 1000;
/**
* the milli seconds of an hour
*/
public static final long HOURMILLI = 60 * 60 * 1000;
/**
* the milli seconds of a minute
*/
public static final long MINUTEMILLI = 60 * 1000;
/**
* the milli seconds of a second
*/
public static final long SECONDMILLI = 1000;
/**
* added time
*/
public static final String TIMETO = " 23:59:59";
/**
* flag before
*/
public static final transient int BEFORE = 1;
/**
* flag after
*/
public static final transient int AFTER = 2;
/**
* flag equal
*/
public static final transient int EQUAL = 3;
/**
* date format dd/MMM/yyyy:HH:mm:ss +0900
*/
public static final String TIME_PATTERN_LONG = "dd/MMM/yyyy:HH:mm:ss +0900";
/**
* date format dd/MM/yyyy:HH:mm:ss +0900
*/
public static final String TIME_PATTERN_LONG2 = "dd/MM/yyyy:HH:mm:ss +0900";
/**
* date format YYYY-MM-DD HH24:MI:SS
*/
public static final String DB_TIME_PATTERN = "YYYY-MM-DD HH24:MI:SS";
/**
* date format YYYYMMDDHH24MISS
*/
public static final String DB_TIME_PATTERN_1 = "YYYYMMDDHH24MISS";
/**
* date format dd/MM/yy HH:mm:ss
*/
public static final String TIME_PATTERN_SHORT = "dd/MM/yy HH:mm:ss";
/**
* date format dd/MM/yy HH24:mm
*/
public static final String TIME_PATTERN_SHORT_1 = "yyyy/MM/dd HH:mm";
/**
* date format yyyy年MM月dd日 HH:mm:ss
*/
public static final String TIME_PATTERN_SHORT_2 = "yyyy年MM月dd日 HH:mm:ss";
/**
* date format yyyyMMddHHmmss
*/
public static final String TIME_PATTERN_SESSION = "yyyyMMddHHmmss";
/**
* date format yyyyMMddHHmmssSSS
*/
public static final String TIME_PATTERN_MILLISECOND = "yyyyMMddHHmmssSSS";
/**
* date format yyyyMMdd
*/
public static final String DATE_FMT_0 = "yyyyMMdd";
/**
* date format yyyy/MM/dd
*/
public static final String DATE_FMT_1 = "yyyy/MM/dd";
/**
* date format yyyy/MM/dd hh:mm:ss
*/
public static final String DATE_FMT_2 = "yyyy/MM/dd hh:mm:ss";
/**
* date format yyyy-MM-dd
*/
public static final String DATE_FMT_3 = "yyyy-MM-dd";
/**
* date format yyyy年MM月dd日
*/
public static final String DATE_FMT_4 = "yyyy年MM月dd日";
/**
* date format yyyy-MM-dd HH
*/
public static final String DATE_FMT_5 = "yyyy-MM-dd HH";
/**
* date format yyyy-MM
*/
public static final String DATE_FMT_6 = "yyyy-MM";
/**
* date format MM月dd日 HH:mm
*/
public static final String DATE_FMT_7 = "MM月dd日 HH:mm";
/**
* date format MM月dd日 HH:mm
*/
public static final String DATE_FMT_8 = "HH:mm:ss";
/**
* date format MM月dd日 HH:mm
*/
public static final String DATE_FMT_9 = "yyyy.MM.dd";
public static final String DATE_FMT_10 = "HH:mm";
public static final String DATE_FMT_11 = "yyyy.MM.dd HH:mm:ss";
/**
* date format yyyy年MM月dd日
*/
public static final String DATE_FMT_12 = "MM月dd日";
public static final String DATE_FMT_13 = "yyyy年MM月dd日HH时mm分";
public static final String DATE_FMT_14 = "yyyyMM";
public static final String DATE_FMT_15 = "MM-dd HH:mm:ss";
public static final String DATE_FMT_16 = "yyyyMMddHHmm";
public static final String DATE_FMT_17 = "HHmmss";
public static final String DATE_FMT_18 = "yyyy";
/**
* date format yyyy-MM-dd HH:mm:ss
*/
public static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

/**
* localDateTime 转 自定义格式string
*
* @param localDateTime
* @param format 例:yyyy-MM-dd hh:mm:ss
* @return
*/
public static String formatLocalDateTimeToString(LocalDateTime localDateTime, String format) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);

} catch (DateTimeParseException e) {
e.printStackTrace();
}
return null;
}

/**
* string 转 LocalDateTime
*
* @param dateStr 例:"2017-08-11 01:00:00"
* @param format 例:"yyyy-MM-dd HH:mm:ss"
* @return
*/
public static LocalDateTime stringToLocalDateTime(String dateStr, String format) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(dateStr, formatter);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
return null;
}


/**
* 根据时间获取当月有多少天数
*
* @param date
* @return
*/
public static int getActualMaximum(Date date) {
return dateToLocalDateTime(date).getMonth().length(dateToLocalDate(date).isLeapYear());
}

/**
* 根据日期获得星期
*
* @param date
* @return 1:星期一;2:星期二;3:星期三;4:星期四;5:星期五;6:星期六;7:星期日;
*/
public static int getWeekOfDate(Date date) {
return dateToLocalDateTime(date).getDayOfWeek().getValue();
}


/**
* 计算两个日期LocalDate相差的天数,不考虑日期前后,返回结果>=0
*
* @param before
* @param after
* @return
*/
public static int getAbsDateDiffDay(LocalDate before, LocalDate after) {
return Math.abs(Period.between(before, after).getDays());
}

/**
* 计算两个时间LocalDateTime相差的天数,不考虑日期前后,返回结果>=0
*
* @param before
* @param after
* @return
*/
public static int getAbsTimeDiffDay(LocalDateTime before, LocalDateTime after) {
return Math.abs(Period.between(before.toLocalDate(), after.toLocalDate()).getDays());
}

/**
* 计算两个时间LocalDateTime相差的月数,不考虑日期前后,返回结果>=0
*
* @param before
* @param after
* @return
*/
public static int getAbsTimeDiffMonth(LocalDateTime before, LocalDateTime after) {
return Math.abs(Period.between(before.toLocalDate(), after.toLocalDate()).getMonths());
}

/**
* 计算两个时间LocalDateTime相差的年数,不考虑日期前后,返回结果>=0
*
* @param before
* @param after
* @return
*/
public static int getAbsTimeDiffYear(LocalDateTime before, LocalDateTime after) {
return Math.abs(Period.between(before.toLocalDate(), after.toLocalDate()).getYears());
}


/**
* 根据传入日期返回星期几
*
* @param date 日期
* @return 1-7 1:星期天,2:星期一,3:星期二,4:星期三,5:星期四,6:星期五,7:星期六
*/
public static int getDayOfWeek(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}

/**
* 获取指定日期的当月的月份数
*
* @param date
* @return
*/
public static int getLastMonth(Date date) {
return dateToLocalDateTime(date).getMonth().getValue();
}

/**
* 特定日期的当月第一天
*
* @param date
* @return
*/
public static LocalDate newThisMonth(Date date) {
LocalDate localDate = dateToLocalDate(date);
return LocalDate.of(localDate.getYear(), localDate.getMonth(), 1);
}

/**
* 特定日期的当月最后一天
*
* @param date
* @return
*/
public static LocalDate lastThisMonth(Date date) {
int lastDay = getActualMaximum(date);
LocalDate localDate = dateToLocalDate(date);
return LocalDate.of(localDate.getYear(), localDate.getMonth(), lastDay);
}

/**
* 特定日期的当年第一天
*
* @param date
* @return
*/
public static LocalDate newThisYear(Date date) {
LocalDate localDate = dateToLocalDate(date);
return LocalDate.of(localDate.getYear(), 1, 1);
}

public static Timestamp getCurrentDateTime() {
return new Timestamp(Instant.now().toEpochMilli());
}

/**
* 获取当前时间
*
* @return LocalDateTime
*/
public static LocalDateTime getCurrentLocalDateTime() {
return LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai")));

}


/**
* 修改日期时间的时间部分
*
* @param date
* @param customTime 必须为"hh:mm:ss"这种格式
*/
public static LocalDateTime reserveDateCustomTime(Date date, String customTime) {
String dateStr = dateToLocalDate(date).toString() + " " + customTime;
return stringToLocalDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
}

/**
* 修改日期时间的时间部分
*
* @param date
* @param customTime 必须为"hh:mm:ss"这种格式
*/
public static LocalDateTime reserveDateCustomTime(Timestamp date, String customTime) {
String dateStr = timestampToLocalDate(date).toString() + " " + customTime;
return stringToLocalDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
}

/**
* 把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
*
* @param date
* @return LocalDateTime
*/
public static final LocalDateTime zerolizedTime(Date date) {
LocalDateTime localDateTime = dateToLocalDateTime(date);
return LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth(), 0, 0, 0, 0);

}

/**
* 把时间变成(yyyy-MM-dd 00:00:00:000)
*
* @param date
* @return LocalDateTime
*/
public static LocalDateTime zerolizedTime(Timestamp date) {
LocalDateTime localDateTime = timestampToLocalDateTime(date);
return LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth(), 0, 0, 0, 0);
}

/**
* 把日期的时间变成(yyyy-MM-dd 23:59:59:999)
*
* @param date
* @return LocalDateTime
*/
public static LocalDateTime getEndTime(Date date) {
LocalDateTime localDateTime = dateToLocalDateTime(date);
return LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth(), 23, 59, 59, 999 * 1000000);
}

/**
* 把时间变成(yyyy-MM-dd 23:59:59:999)
*
* @param date
* @return LocalDateTime
*/
public static LocalDateTime getEndTime(Timestamp date) {
LocalDateTime localDateTime = timestampToLocalDateTime(date);
return LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth(), 23, 59, 59, 999 * 1000000);
}

/**
* 计算特定时间到 当天 23.59.59.999 的秒数
*
* @return
*/
public static int calculateToEndTime(Date date) {
LocalDateTime localDateTime = dateToLocalDateTime(date);
LocalDateTime end = getEndTime(date);
return (int) (end.toEpochSecond(ZoneOffset.UTC) - localDateTime.toEpochSecond(ZoneOffset.UTC));
}


/**
* 增加或减少年/月/周/天/小时/分/秒数
*
* @param localDateTime 例:ChronoUnit.DAYS
* @param chronoUnit
* @param num
* @return LocalDateTime
*/
public static LocalDateTime addTime(LocalDateTime localDateTime, ChronoUnit chronoUnit, int num) {
return localDateTime.plus(num, chronoUnit);
}

/**
* 增加或减少年/月/周/天/小时/分/秒数
*
* @param chronoUnit 例:ChronoUnit.DAYS
* @param num
* @return LocalDateTime
*/
public static LocalDateTime addTime(Date date, ChronoUnit chronoUnit, int num) {
long nanoOfSecond = (date.getTime() % 1000) * 1000000;
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000, (int) nanoOfSecond, ZoneOffset.of("+8"));
return localDateTime.plus(num, chronoUnit);
}

/**
* 增加或减少年/月/周/天/小时/分/秒数
*
* @param chronoUnit 例:ChronoUnit.DAYS
* @param num
* @return LocalDateTime
*/
public static LocalDateTime addTime(Timestamp date, ChronoUnit chronoUnit, int num) {
long nanoOfSecond = (date.getTime() % 1000) * 1000000;
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000, (int) nanoOfSecond, ZoneOffset.of("+8"));
return localDateTime.plus(num, chronoUnit);
}

/**
* Date 转 LocalDateTime
*
* @param date
* @return LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
long nanoOfSecond = (date.getTime() % 1000) * 1000000;
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000, (int) nanoOfSecond, ZoneOffset.of("+8"));
return localDateTime;
}

/**
* Timestamp 转 LocalDateTime
*
* @param date
* @return LocalDateTime
*/
public static LocalDateTime timestampToLocalDateTime(Timestamp date) {
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000, date.getNanos(), ZoneOffset.of("+8"));
return localDateTime;
}

/**
* Date 转 LocalDateTime
*
* @param date
* @return LocalDate
*/
public static LocalDate dateToLocalDate(Date date) {
return dateToLocalDateTime(date).toLocalDate();
}

/**
* timestamp 转 LocalDateTime
*
* @param date
* @return LocalDate
*/
public static LocalDate timestampToLocalDate(Timestamp date) {
return timestampToLocalDateTime(date).toLocalDate();
}

/**
* 比较两个LocalDateTime是否同一天
*
* @param begin
* @param end
* @return
*/
public static boolean isTheSameDay(LocalDateTime begin, LocalDateTime end) {
return begin.toLocalDate().equals(end.toLocalDate());
}


/**
* 比较两个时间LocalDateTime大小
*
* @param time1
* @param time2
* @return 1:第一个比第二个大;0:第一个与第二个相同;-1:第一个比第二个小
*/
public static int compareTwoTime(LocalDateTime time1, LocalDateTime time2) {
if (time1.isAfter(time2)) {
return 1;
} else if (time1.isBefore(time2)) {
return -1;
} else {
return 0;
}
}


/**
* 比较time1,time2两个时间相差的秒数,如果time1<=time2,返回0
*
* @param time1
* @param time2
*/
public static long getTwoTimeDiffSecond(Timestamp time1, Timestamp time2) {
long diff = timestampToLocalDateTime(time1).toEpochSecond(ZoneOffset.UTC) - timestampToLocalDateTime(time2).toEpochSecond(ZoneOffset.UTC);
if (diff > 0) {
return diff;
} else {
return 0;
}
}

/**
* 比较time1,time2两个时间相差的分钟数,如果time1<=time2,返回0
*
* @param time1
* @param time2
*/
public static long getTwoTimeDiffMin(Timestamp time1, Timestamp time2) {
long diff = getTwoTimeDiffSecond(time1, time2) / 60;
if (diff > 0) {
return diff;
} else {
return 0;
}
}

/**
* 比较time1,time2两个时间相差的小时数,如果time1<=time2,返回0
*
* @param time1
* @param time2
*/
public static long getTwoTimeDiffHour(Timestamp time1, Timestamp time2) {
long diff = getTwoTimeDiffSecond(time1, time2) / 3600;
if (diff > 0) {
return diff;
} else {
return 0;
}
}

/**
* 判断当前时间是否在时间范围内
*
* @param startTime
* @param endTime
* @return
*/
public static boolean isTimeInRange(Date startTime, Date endTime) throws Exception {
LocalDateTime now = getCurrentLocalDateTime();
LocalDateTime start = dateToLocalDateTime(startTime);
LocalDateTime end = dateToLocalDateTime(endTime);
return (start.isBefore(now) && end.isAfter(now)) || start.isEqual(now) || end.isEqual(now);
}

}

以上就是Jdk8中的时间操作,mybatis默认不支持,需要添加(mybatis 3.4.0版本):

1
2
3
4
5
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-typehandlers-jsr310</artifactId>
<version>1.0.1</version>
</dependency>

配置好这个依赖之后,就可以把Entity里面的Date替换成LocalDate、LocalDateTime了,其他的不用改

1
2
3
4
5
6
public class User {
private Integer id;
private String name;
private LocalDate createDate;
private LocalDateTime createTime;
}

一般来说,简单时间操作方法是均转换成localDateTime,然后在进行操作:

1
2
3
4
Date date = new Date();
LocalDateTime localDateTime1 = LocalDateTime.ofInstant(date.toInstant(),ZoneOffset.of("+8")); //统一转化为localdatetime进行处理
LocalDateTime localDateTime2 = LocalDateTime.of(localDateTime1.getYear(),localDateTime1.getMonth(), 1, 0, 0, 0); //转换为标准时间,带 分和秒
startDay = localDateTime2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); //转换为String类型

获取简称工具类

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
public class CityUtil {
//暴力方式1
public static String getShortName(String address){
String province = null;
String regex = "(.*?)省";
String regex2 = "(.*?)市";
String regex3 = "(.*?)自治区";
String regex4 = "(.*?)特别行政区";
String regex5 = "(.*?)壮族自治区";
String regex6 = "(.*?)回族自治区";
String regex7 = "(.*?)维吾尔自治区";
String regex8 = "(.*?)地区";
Matcher m = Pattern.compile(regex).matcher(address);
while (m.find()) {
province = m.group(1);
}
Matcher m2 = Pattern.compile(regex2).matcher(address);
while (m2.find()) {
province = m2.group(1);
}
Matcher m3 = Pattern.compile(regex3).matcher(address);
while (m3.find()) {
province = m3.group(1);
}
... //依次类推...
return province;
}
//暴力方式2
public static String getShortName2(String address){
String name = address;
if("北京市".equals(address)){
name = "北京";
}
if("新疆维吾尔自治区".equals(fieldName)){
name = "新疆";
}
... //依次类推...
return name;
}
//期待更好的方式
}

Token管理类

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
public class TokenManager {

private static String token = null;

/**
* 上次获取access_token时间
*/
private static Long lastGetAccessTokenTime = 0L;

/**
* 过期时间
*/
private static Long expires_in = 7100L;

public static String getAccessToken() {
Long currentTime = System.currentTimeMillis();
if (ticket == null) {
return refreshAccessToken();
} else {
if ((currentTime - lastGetAccessTokenTime)/ 1000 > expires_in) {
return refreshAccessToken();
}
}
return TokenManager.token;
}

/**
* 刷新 ticket
* @return
*/
public static String refreshAccessToken() {
lastGetAccessTokenTime = System.currentTimeMillis();
String time = String.valueOf(System.currentTimeMillis());
//获取token传参,自行修改
Map<String, Object> params = new HashMap<>();
params.put("sysmark", UrlContent.DEFAULT_SYSMARK);
params.put("time", time);
params.put("sign", Md5Util.encode(UrlContent.DEFAULT_SYSMARK+UrlContent.DEFAULT_SYSWORD+time));
String url = UrlContent.AUTH_TICKET_URL +"?sysmark={sysmark}&time={time}&sign={sign}";
String result = HttpClientUtils.getTokenResult(url,params);
TicketManager.ticket = result;
return ticket;
}

public static void main(String[] args) {
refreshAccessToken();
}
}

HttpClient工具类

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
public class HttpClientUtils {

@Autowired
RestTemplate client;

private static RestTemplate restTemplate;

@PostConstruct
public void init() {
restTemplate = client;
}

public static String postResult(String url,Map<String,Object> params){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
log.info("url==>>{}<== params==>>{}",url,params);
String result = restTemplate.postForEntity(url,requestEntity,String.class).getBody();
log.info("post result==>>{}",result);
return result;
}

public static String getTokenResult(String url,Map<String,Object> params){
JSONObject jsonObject = getResultInfo(url,params);
String token = jsonObject.get("token").toString();
log.info("token:{}"+token);
return ticket;
}

public static String getResult(String url,Map<String,Object> params){
JSONObject jsonObject = getResultInfo(url,params);
String data = jsonObject.get("data").toString();
log.info("data:{}"+data);
return data;
}

private static JSONObject getResultInfo(String url,Map<String,Object> params){
log.info("url==>>{}<== params==>>{}",url,params);
ResponseEntity<String> result =null;
try{
result = restTemplate.getForEntity(url,String.class,params);
}catch(Exception e){
log.error(e);
}
JSONObject jsonObject = JSON.parseObject(result.getBody());
return jsonObject;
}
}

图片验证码–kaptcha实现

以springBoot项目为例
kaptcha 是生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比。

1、添加依赖:

1
2
3
4
5
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>

2、定义KaptchaConfiguration:

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
@Configuration
public class KaptchaConfiguration {

private static final String KAPTCHA_BORDER = "kaptcha.border";
private static final String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";
private static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";
private static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";
private static final Object KAPTCHA_IMAGE_FONT_SIZE = "kaptcha.textproducer.font.size";

/**
* 默认生成图形验证码宽度
*/
private static final String DEFAULT_IMAGE_WIDTH = "100";

/**
* 默认生成图像验证码高度
*/
private static final String DEFAULT_IMAGE_HEIGHT = "40";

/**
* 默认生成图形验证码长度
*/
private static final String DEFAULT_IMAGE_LENGTH = "4";
/**
* 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
*/
private static final String DEFAULT_COLOR_FONT = "black";

/**
* 图片边框
*/
private static final String DEFAULT_IMAGE_BORDER = "no";
/**
* 默认图片间隔
*/
private static final String DEFAULT_CHAR_SPACE = "5";
/**
* 验证码文字大小
*/
private static final String DEFAULT_IMAGE_FONT_SIZE = "30";

@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put(KAPTCHA_BORDER, DEFAULT_IMAGE_BORDER);
properties.put(KAPTCHA_TEXTPRODUCER_FONT_COLOR, DEFAULT_COLOR_FONT);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, DEFAULT_CHAR_SPACE);
properties.put(KAPTCHA_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH);
properties.put(KAPTCHA_IMAGE_HEIGHT, DEFAULT_IMAGE_HEIGHT);
properties.put(KAPTCHA_IMAGE_FONT_SIZE, DEFAULT_IMAGE_FONT_SIZE);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, DEFAULT_IMAGE_LENGTH);
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}

3、添加处理类:

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
@ReController
public class KcaptchaController {

@Autowired
private Producer captchaProducer;

@GetMapping("getKaptchaImage")
public void getKaptchaImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {

response.setDateHeader("Expires", 0);

// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}

文章作者: gqsu
文章链接: http://www.ipdax.com/2018/05/16/util-时间工具类、httpclient工具类/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 技术笔记分享
支付宝打赏
微信打赏