Repository navigation
Expand file tree
/
Copy pathsearch.xml
More file actions
719 lines (719 loc) · 336 KB
/
Copy pathsearch.xml
File metadata and controls
719 lines (719 loc) · 336 KB
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
<?xml version="1.0" encoding="utf-8"?>
<search>
<entry>
<title><![CDATA[懒人专用,全网VIP视频免费破解去广告、全网音乐直接下载、百度网盘直接下载、知乎视频下载]]></title>
<url>%2F2019%2F12%2F14%2F%E6%87%92%E4%BA%BA%E4%B8%93%E7%94%A8%EF%BC%8C%E5%85%A8%E7%BD%91VIP%E8%A7%86%E9%A2%91%E5%85%8D%E8%B4%B9%E7%A0%B4%E8%A7%A3%E5%8E%BB%E5%B9%BF%E5%91%8A%E3%80%81%E5%85%A8%E7%BD%91%E9%9F%B3%E4%B9%90%E7%9B%B4%E6%8E%A5%E4%B8%8B%E8%BD%BD%E3%80%81%E7%99%BE%E5%BA%A6%E7%BD%91%E7%9B%98%E7%9B%B4%E6%8E%A5%E4%B8%8B%E8%BD%BD%E3%80%81%E7%9F%A5%E4%B9%8E%E8%A7%86%E9%A2%91%E4%B8%8B%E8%BD%BD%2F</url>
<content type="text"><![CDATA[IDM+油猴\1. 在https://www.extfans.com/上下载油猴 \2. 谷歌浏览器选择开发者模式 \3. 解压油猴,把crx文件拖到浏览器的拓展程序界面(如果无法安装把浏览器关了重开就可以了) \4. 安装插件 \5. 安装IDM \6. 安装完成以后谷歌会自动提示添加IDM插件,也可以自己照着教程添加 开始下载]]></content>
<categories>
<category>IDM+油猴破解</category>
</categories>
<tags>
<tag>IDM+油猴破解</tag>
</tags>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录二十-IDEA中创建和启动SpringBoot应用的正确姿势]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%BA%8C%E5%8D%81-IDEA%E4%B8%AD%E5%88%9B%E5%BB%BA%E5%92%8C%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E6%AD%A3%E7%A1%AE%E5%A7%BF%E5%8A%BF%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十九-使用Seata彻底解决Spring Cloud中的分布式事务问题!]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%B9%9D-%E4%BD%BF%E7%94%A8Seata%E5%BD%BB%E5%BA%95%E8%A7%A3%E5%86%B3Spring-Cloud%E4%B8%AD%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1%E9%97%AE%E9%A2%98%EF%BC%81%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十八-Spring Cloud Alibaba:Sentinel实现熔断与限流]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E5%85%AB-Spring-Cloud-Alibaba%EF%BC%9ASentinel%E5%AE%9E%E7%8E%B0%E7%86%94%E6%96%AD%E4%B8%8E%E9%99%90%E6%B5%81%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[和配置中心使用]]></title>
<url>%2F2019%2F12%2F07%2F%E5%92%8C%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%E4%BD%BF%E7%94%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十七-Spring Cloud Alibaba:Nacos 作为注册中心和配置中心使用]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%B8%83-Spring-Cloud-Alibaba%EF%BC%9ANacos-%E4%BD%9C%E4%B8%BA%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83%E5%92%8C%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%E4%BD%BF%E7%94%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十六-Spring Cloud Security:Oauth2实现单点登录]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E5%85%AD-Spring-Cloud-Security%EF%BC%9AOauth2%E5%AE%9E%E7%8E%B0%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十五-Spring Cloud Security:Oauth2结合JWT使用]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%BA%94-Spring-Cloud-Security%EF%BC%9AOauth2%E7%BB%93%E5%90%88JWT%E4%BD%BF%E7%94%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十四-Spring Cloud Security:Oauth2使用入门]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E5%9B%9B-Spring-Cloud-Security%EF%BC%9AOauth2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十三-Spring Boot Admin:微服务应用监控]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%B8%89-Spring-Boot-Admin-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E5%BA%94%E7%94%A8%E7%9B%91%E6%8E%A7%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十二-Spring Cloud Gateway:新一代API网关服务]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%BA%8C-Spring-Cloud-Gateway-%E6%96%B0%E4%B8%80%E4%BB%A3API%E7%BD%91%E5%85%B3%E6%9C%8D%E5%8A%A1%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十一-Spring Cloud Consul:服务治理与配置中心]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81%E4%B8%80-Spring-Cloud-Consul-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86%E4%B8%8E%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录十-Spring Cloud Sleuth:分布式请求链路跟踪]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%8D%81-Spring-Cloud-Sleuth-%E5%88%86%E5%B8%83%E5%BC%8F%E8%AF%B7%E6%B1%82%E9%93%BE%E8%B7%AF%E8%B7%9F%E8%B8%AA%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录九-Spring Cloud Bus:消息总线]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%B9%9D-Spring-Cloud-Bus%EF%BC%9A%E6%B6%88%E6%81%AF%E6%80%BB%E7%BA%BF%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录八-Spring Cloud Config:外部集中化配置管理]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%85%AB-Spring-Cloud-Config%EF%BC%9A%E5%A4%96%E9%83%A8%E9%9B%86%E4%B8%AD%E5%8C%96%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录七-Spring Cloud Zuul:API网关服务]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%B8%83-Spring-Cloud-Zuul%EF%BC%9AAPI%E7%BD%91%E5%85%B3%E6%9C%8D%E5%8A%A1%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录六-Spring Cloud OpenFeign:基于Ribbo n和Hystrix的声明式服务调用]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%85%AD-Spring-Cloud-OpenFeign-%E5%9F%BA%E4%BA%8ERibbo-n%E5%92%8CHystrix%E7%9A%84%E5%A3%B0%E6%98%8E%E5%BC%8F%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录五-Hystrix Dashboard:断路器执行监控]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%BA%94-Hystrix-Dashboard-%E6%96%AD%E8%B7%AF%E5%99%A8%E6%89%A7%E8%A1%8C%E7%9B%91%E6%8E%A7%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录四-Spring Cloud Hystrix:服务容错保护]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E5%9B%9B-Spring-Cloud-Hystrix-%E6%9C%8D%E5%8A%A1%E5%AE%B9%E9%94%99%E4%BF%9D%E6%8A%A4%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录三-Spring Cloud Ribbon:负载均衡的服务调用]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%B8%89-Spring-Cloud-Ribbon-%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%9A%84%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录二-SpringCloud Eureka:服务注册与发现]]></title>
<url>%2F2019%2F12%2F07%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%BA%8C-SpringCloud-Eureka-%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E4%B8%8E%E5%8F%91%E7%8E%B0%2F</url>
<content type="text"></content>
</entry>
<entry>
<title><![CDATA[SpringCloud学习教程目录一:SpringCloud整体架构概览]]></title>
<url>%2F2019%2F12%2F06%2FSpringCloud%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95%E4%B8%80-SpringCloud%E6%95%B4%E4%BD%93%E6%9E%B6%E6%9E%84%E6%A6%82%E8%A7%88%2F</url>
<content type="text"><![CDATA[SpringCloud整体架构概览原创: 梦想de星空 macrozheng 9月9日 什么是SpringCloud目标协调任何服务,简化分布式系统开发。 简介构建分布式系统不应该是复杂的,SpringCloud对常见的分布式系统模式提供了简单易用的编程模型,帮助开发者构建弹性、可靠、协调的应用程序。SpringCloud是在SpringBoot的基础上构建的,使开发者可以轻松入门并快速提高工作效率。SpringCloud为开发人员提供了快速构建分布式系统架构的工具,例如配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁定,领导选举,分布式会话,集群状态等。 整体架构 来自Spring官网 SpringCloud的版本关系SpringCloud是一个由许多子项目组成的综合项目,各子项目有不同的发布节奏。为了管理SpringCloud与各子项目的版本依赖关系,发布了一个清单,其中包括了某个SpringCloud版本对应的子项目版本。为了避免SpringCloud版本号与子项目版本号混淆,SpringCloud版本采用了名称而非版本号的命名,这些版本的名字采用了伦敦地铁站的名字,根据字母表的顺序来对应版本时间顺序,例如Angel是第一个版本, Brixton是第二个版本。当SpringCloud的发布内容积累到临界点或者一个重大BUG被解决后,会发布一个”service releases”版本,简称SRX版本,比如Greenwich.SR2就是SpringCloud发布的Greenwich版本的第2个SRX版本。 SpringCloud和SpringBoot版本对应关系 SpringCloud Version SpringBoot Version Hoxton 2.2.x Greenwich 2.1.x Finchley 2.0.x Edgware 1.5.x Dalston 1.5.x SpringCloud和各子项目版本对应关系 Component Edgware.SR6 Greenwich.SR2 spring-cloud-bus 1.3.4.RELEASE 2.1.2.RELEASE spring-cloud-commons 1.3.6.RELEASE 2.1.2.RELEASE spring-cloud-config 1.4.7.RELEASE 2.1.3.RELEASE spring-cloud-netflix 1.4.7.RELEASE 2.1.2.RELEASE spring-cloud-security 1.2.4.RELEASE 2.1.3.RELEASE spring-cloud-consul 1.3.6.RELEASE 2.1.2.RELEASE spring-cloud-sleuth 1.3.6.RELEASE 2.1.1.RELEASE spring-cloud-stream Ditmars.SR5 Fishtown.SR3 spring-cloud-zookeeper 1.2.3.RELEASE 2.1.2.RELEASE spring-boot 1.5.21.RELEASE 2.1.5.RELEASE spring-cloud-task 1.2.4.RELEASE 2.1.2.RELEASE spring-cloud-gateway 1.0.3.RELEASE 2.1.2.RELEASE spring-cloud-openfeign 暂无 2.1.2.RELEASE 注意:Greenwich版本是基于SpringBoot 2.1.x版本构建的,不适用于1.5.x版本。随着2019年8月SpringBoot 1.5.x版本停止维护,Edgware版本也将停止维护。 SpringCloud子项目简介Spring Cloud Config集中配置管理工具,分布式系统中统一的外部配置管理,默认使用Git来存储配置,可以支持客户端配置的刷新及加密、解密操作。 Spring Cloud NetflixNetflix OSS 开源组件集成,包括Eureka、Hystrix、Ribbon、Feign、Zuul等核心组件。 Eureka:服务治理组件,包括服务端的注册中心和客户端的服务发现机制; Ribbon:负载均衡的服务调用组件,具有多种负载均衡调用策略; Hystrix:服务容错组件,实现了断路器模式,为依赖服务的出错和延迟提供了容错能力; Feign:基于Ribbon和Hystrix的声明式服务调用组件; Zuul:API网关组件,对请求提供路由及过滤功能。 Spring Cloud Bus用于传播集群状态变化的消息总线,使用轻量级消息代理链接分布式系统中的节点,可以用来动态刷新集群中的服务配置。 Spring Cloud Consul基于Hashicorp Consul的服务治理组件。 Spring Cloud Security安全工具包,对Zuul代理中的负载均衡OAuth2客户端及登录认证进行支持。 Spring Cloud SleuthSpringCloud应用程序的分布式请求链路跟踪,支持使用Zipkin、HTrace和基于日志(例如ELK)的跟踪。 Spring Cloud Stream轻量级事件驱动微服务框架,可以使用简单的声明式模型来发送及接收消息,主要实现为Apache Kafka及RabbitMQ。 Spring Cloud Task用于快速构建短暂、有限数据处理任务的微服务框架,用于向应用中添加功能性和非功能性的特性。 Spring Cloud Zookeeper基于Apache Zookeeper的服务治理组件。 Spring Cloud GatewayAPI网关组件,对请求提供路由及过滤功能。 Spring Cloud OpenFeign基于Ribbon和Hystrix的声明式服务调用组件,可以动态创建基于Spring MVC注解的接口实现用于服务调用,在SpringCloud 2.0中已经取代Feign成为了一等公民。 后续后续SpringCloud系列教程将采用SpringCloud的最新版本Greenwich.SR2来讲解,大家保持关注! 推荐阅读 Hutool中那些常用的工具类和方法 Java 8都出那么久了,Stream API了解下? SpringBoot Admin 2.0 详解 IDEA中的Git操作,看这一篇就够了! 10分钟搭建自己的Git仓库 那些年,我们见过的 Java 服务端乱象 我的Github开源项目,从0到20000 Star! 欢迎关注,点个在看 梦想de星空 转发和在看是对作者最大的支持]]></content>
<categories>
<category>mall-spring cloud</category>
</categories>
<tags>
<tag>mall-spring cloud</tag>
</tags>
</entry>
<entry>
<title><![CDATA[3.Spring Cloud中服务的发现与消费]]></title>
<url>%2F2019%2F12%2F03%2F3-Spring-Cloud%E4%B8%AD%E6%9C%8D%E5%8A%A1%E7%9A%84%E5%8F%91%E7%8E%B0%E4%B8%8E%E6%B6%88%E8%B4%B9%2F</url>
<content type="text"></content>
<categories>
<category>微服务</category>
</categories>
<tags>
<tag>Spring Cloud</tag>
</tags>
</entry>
<entry>
<title><![CDATA[jnydy-使用Spring Cloud搭建高可用服务注册中心]]></title>
<url>%2F2019%2F12%2F03%2Fjnydy-%E4%BA%8C%E3%80%81%E4%BD%BF%E7%94%A8Spring-Cloud%E6%90%AD%E5%BB%BA%E9%AB%98%E5%8F%AF%E7%94%A8%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83%2F</url>
<content type="text"><![CDATA[jnydy-二、使用Spring Cloud搭建高可用服务注册中心我们需要的,不仅仅是一个服务注册中心而已,而是一个高可用服务注册中心。 上篇博客【使用Spring Cloud搭建服务注册中心】中我们介绍了如何使用Spring Cloud搭建一个服务注册中心,但是搭建好的服务注册中心是一个单节点的服务注册中心,这样一旦发生了故障,那么整个服务就会瘫痪,所以我们需要一个高可用的服务注册中心,那么在Eureka中,我们通过集群来解决这个问题。Eureka Server的高可用实际上就是将自己作为服务向其他服务注册中心注册自己,这样就会形成一组互相注册的服务注册中心,进而实现服务清单的互相同步,达到高可用的效果。OK,由于本文的效果是在上篇博客【使用Spring Cloud搭建服务注册中心】的基础上实现的,所以建议小伙伴们先阅读上文,否则本文阅读可能会没有头绪。OK,废话不多说,我们就来看看如何搭建高可用注册中心。增加配置文件在上篇博客中,我们创建了一个名叫eureka-server的服务注册中心,那么在本文中,我将修改这个工程的配置文件,进而将其启动多次。如下,我向这个工程中添加两个配置文件application-peer1.properties和application-peer2.properties: 两个配置文件的内容分别如下:application-peer1.properties:server.port=1111 eureka.instance.hostname=peer1 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.client.service-url.defaultZone=http://peer2:1112/eureka/application-peer2.properties:server.port=1112 eureka.instance.hostname=peer2 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.client.service-url.defaultZone=http://peer1:1111/eureka/关于这两个配置文件我说如下几点:1.在peer1的配置文件中,让它的service-url指向peer2,在peer2的配置文件中让它的service-url指向peer12.为了让peer1和peer2能够被正确的访问到,我们需要在C:\Windows\System32\drivers\etc目录下的hosts文件总添加两行配置,如下:127.0.0.1 peer1127.0.0.1 peer23.由于peer1和peer2互相指向对方,实际上我们构建了一个双节点的服务注册中心集群生成jar文件OK,这次我们不直接从IDEA中启动项目,而是先给工程生成jar文件,生成方式如下,双击package生成: 生成结果如下: 启动项目生成jar文件之后,我们在命令行通过java命令来启动项目,在启动的时候我们可以设置采用不同的配置文件来启动项目,命令如下:java -jar eureka-server-0.0.1-SNAPSHOT.jar –spring.profiles.active=peer1 java -jar eureka-server-0.0.1-SNAPSHOT.jar –spring.profiles.active=peer2这两行命令表示我们分别采用application-peer1.properties和application-peer2.properties两个配置文件来启动应用,OK,执行完这两个命令之后,我们的服务注册中心就启动了两个了,效果图如下: 我们可以看到,在peer1的节点的DS replicas我们已经可以看到peer2节点了,在peer2的DS replicas中我们也可以看到peer1节点了。OK,如此之后,我们的服务注册中心集群就搭建好了,然后我们可以做一个简单的测试。测试修改上篇博客中提到的provider项目的配置文件,如下:spring.application.name=hello-service eureka.client.service-url.defaultZone=http://peer1:1111/eureka,http://peer2:1112/eureka小伙伴们注意,我们在service-url中添加了两个注册中心地址,两个地址中间用,隔开,OK,修改一下这里就可以了,接下来我们来启动这个项目,启动成功之后我们再去刷新http://localhost:1111和http://localhost:1112 两个页面,我们会发现我的服务提供者在这两个服务注册中心都注册了,如下: OK,至此,一个高可用的服务注册中心我们就搭建成功了,有问题欢迎留言讨论。下篇文章我们就来看看Spring Cloud中服务的发现与消费本文案例地址:https://github.com/lenve/Simple]]></content>
<categories>
<category>微服务</category>
</categories>
<tags>
<tag>Spring Cloud</tag>
</tags>
</entry>
<entry>
<title><![CDATA[使用Spring Cloud搭建服务注册中心]]></title>
<url>%2F2019%2F11%2F30%2Fjnydy-%E4%B8%80%E3%80%81%E4%BD%BF%E7%94%A8Spring-Cloud%E6%90%AD%E5%BB%BA%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83%2F</url>
<content type="text"><![CDATA[jnydy-一、使用Spring Cloud搭建服务注册中心本文转载自:https://mp.weixin.qq.com/s/K-WDRVLh-AFda_g7ga4iwA 原创: sang 江南一点雨 2017-09-03 我们在之前的博客中已经介绍过阿里的分布式服务框架dubbo【Linux上安装Zookeeper以及一些注意事项】【一个简单的案例带你入门Dubbo分布式框架】,但是小伙伴们应该也看到了,阿里的dubbo无法单独完成工作,我们还要借助于Apache上的开源框架zookeeper(不是必须,但是最佳实践莫过于zookeeper),使用zookeeper作为服务注册中心,才能实现一个较好的分布式应用。与dubbo不同的是,Spring Cloud是一个一站式分布式框架,Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。分布式系统的协调导致了样板模式, 使用Spring Cloud开发人员可以快速地支持实现这些模式的服务和应用程序。他们将在任何分布式环境中运行良好,包括开发人员自己的笔记本电脑,裸机数据中心,以及Cloud Foundry等托管平台。那么今天我希望通过一个简单的案例带小伙伴们来了解下Spring Cloud。 OK,那么本文我主要想介绍下在Spring Cloud中使用Eureka搭建一个服务注册中心,然后再向其中注册服务。由于Spring Cloud是在Spring Boot的基础上构建分布式服务的,所以阅读本文需要有一点Spring Boot的知识储备,如果小伙伴们对Spring Boot尚不太熟悉的话,可以先参考下【https://github.com/lenve/JavaEETest】。OK,那么上面所提到的是阅读本文所需要具备的基础知识,在此基础之上我们来看看怎么样利用Spring Cloud中的Eureka来搭建服务注册中心。 首先我要说的是Spring Cloud并不是一个东西,和Hadoop类似,Spring Cloud也包含了许多个子项目,我们今天要看的Eureka只是其中的一个子项目,Eureka的功能有点类似于我们之前写过的zookeeper,它是一个服务治理组件,包含了服务注册中心、服务注册与发现机制。其他的组件我们这里先不做介绍,后面的系列文章都会一一提及到。 OK,废话说了一箩筐,上代码吧。 创建服务注册中心创建一个普通的Spring Boot工程首先我们需要创建一个普通的Spring Boot工程,命名为eureka-server,普通到什么程度呢?就是一个starter都不需要添加,创建成功之后就只引用了一个父starter。 添加Eureka依赖工程创建成功之后,向pom.xml文件中添加eureka-server的依赖,目前eureka的稳定版本是Dalston.SR3,添加完依赖之后,pom.xml文件如下所示: 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.sang</groupId> <artifactId>eureka-server</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eureka-server</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> 那么这里依赖的添加我主要参考了Eureka官网的 http://projects.spring.io/spring-cloud/。 启动一个服务注册中心启动一个服务注册中心的方式很简单,就是在Spring Boot的入口类上添加一个@EnableEurekaServer注解,如下: 1234567@EnableEurekaServer@SpringBootApplicationpublic class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); }} 配置服务注册中心最后我们再做一点简单的配置就可以了,配置就写在Spring Boot的配置文件application.properties中,写法如下: 12345server.port=1111eureka.instance.hostname=localhosteureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/ OK,那么关于这几行注释,我说如下几点: 1.server.port=1111表示设置该服务注册中心的端口号2.eureka.instance.hostname=localhost表示设置该服务注册中心的hostname3.eureka.client.register-with-eureka=false,由于我们目前创建的应用是一个服务注册中心,而不是普通的应用,默认情况下,这个应用会向注册中心(也是它自己)注册它自己,设置为false表示禁止这种默认行为4.eureka.client.fetch-registry=false,表示不去检索其他的服务,因为服务注册中心本身的职责就是维护服务实例,它也不需要去检索其他服务 测试OK,做完这一切之后,我们就可以启动这一个Spring Boot 服务,服务启动成功之后,在浏览器中输入:http://localhost:1111就能够看到如下页面: OK,看到上面这个页面之后,表示你的服务注册中心已经搭建好了。 小结我们之前专门有一篇博客介绍如何在Linux上安装zookeeper【Linux上安装Zookeeper以及一些注意事项】,但是对于Eureka却不存在这样的问题,因为Eureka中的服务注册中心实际上是一个Spring Boot工程,而Spring Boot工程我们知道可以直接打成一个jar包,然后java -jar命令就可以运行,不管Windows还是Linux上,运行方式都是一致的。 注册服务提供者OK,那么现在服务注册中心有了之后,我们可以考虑向这个服务注册中心注册一个服务提供者了。 创建一个新的Spring Boot工程还是创建一个Spring Boot工程,这次创建比之前创建多一个步骤,在创建的时候选中web的starter,我们来创建一个web工程,在IntelliJ IDEA中创建的时候选中web,如下: 添加Eureka依赖在创建好的工程中,我们需要添加Eureka依赖,添加方式如下: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.sang</groupId> <artifactId>provider</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>provider</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> 创建应用的入口这是一个web工程,所以我们添加一个Controller,在该Controller中提供一个访问入口,如下: 123456789101112131415@RestControllerpublic class HelloController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private DiscoveryClient client; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String index() { List<ServiceInstance> instances = client.getInstances("hello-service"); for (int i = 0; i < instances.size(); i++) { logger.info("/hello,host:" + instances.get(i).getHost() + ",service_id:" + instances.get(i).getServiceId()); } return "Hello World"; }} 这里创建服务之后,在日志中将服务相关的信息打印出来。 激活Eureka中的DiscoveryClient在Spring Boot的入口函数处,通过添加@EnableDiscoveryClient注解来激活Eureka中的DiscoveryClient实现(因为我们在HelloController中注入了DiscoveryClient)。 12345678@EnableDiscoveryClient@SpringBootApplicationpublic class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); }} 配置服务名称和注册中心地址最后的最后,我们在application.properties文件中配置一下服务名和注册中心地址即可,如下: 12spring.application.name=hello-serviceeureka.client.service-url.defaultZone=http://localhost:1111/eureka 这两行代码的含义很简单,我就不多说了。 测试做完这一切之后,我们就可以来测试了,直接运行这个Spring Boot工程,运行成功之后,我们刷新刚才的http://localhost:1111,就可以看到有一个服务已经注册成功了。如下: 同时,我们查看这个服务提供者运行日志,也可以看到服务的信息,如下: 小结OK,如此之后,我们一个服务注册中心就搭建成功了,同时也有一个服务提供者成功的注册了。但是这样还有一个小问题,那就是我们这里是一个单节点的服务注册中心,一旦发生了故障整个服务就瘫痪了,所以在实际应用中,我们需要搭建高可用注册中心,那么关于高可用注册中心如何搭建的问题,我们将在下篇文章中来介绍。 本文案例地址:https://github.com/lenve/SimpleSpringCloud 更多JavaEE资料请关注公众号: 以上。。]]></content>
<categories>
<category>微服务</category>
</categories>
<tags>
<tag>Spring Cloud</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring MVC表单验证器的使用]]></title>
<url>%2F2019%2F08%2F27%2FSpring-MVC%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81%E5%99%A8%E7%9A%84%E4%BD%BF%E7%94%A8%2F</url>
<content type="text"><![CDATA[SpringMVC表单验证器的使用本章讲解SpringMVC中怎么通过注解对表单参数进行验证。 SpringBoot配置使用springboot, spring-boot-starter-web会自动引入 hiberante-validator, validation-api依赖。 在 WebMvcConfigurerAdapter实现类里面添加验证器及国际化指定资源文件。 1234567891011@Overridepublic Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); return validator;}@Beanpublic MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("i18n/ValidationMessages"); messageSource.setDefaultEncoding(StandardCharsets.US_ASCII.name()); return messageSource;} 验证器使用接收参数的表单类: 1234567891011121314151617181920public class LoginForm { @NotNull(message = "{login.loginName.length}") @Size(min = 4, max = 20, message = "{login.loginName.length}") private String loginName; @NotNull(message = "{login.loginPassword.length}") @Size(min = 8, max = 20, message = "{login.loginPassword.length}") private String loginPassword; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; }} 在要验证的字段上面加入验证注解,更多参考 validation-apijar包下的 javax.validation.constraints包。 SpringMVC控制器: 123@PostMapping(value = "/login")public String login(@Validated LoginForm form) { ...} 使用 @Validated注解表示该参数需要验证。 国际化message里面 {}引用的是国际化的资源。 添加国际化资源文件: ValidationMessages.properties ValidationMessageszhCN.properties 需要指定编码为 ASCII,不然会乱码。 异常处理异常全局处理时进行处理: 123456789101112131415@ControllerAdvicepublic class ExceptionResolver { @ExceptionHandler(Throwable.class) @ResponseBody Object handleEntityException(HttpServletRequest request, Throwable ex) { ... if (ex instanceof BindException) { BindException c = (BindException) ex; List<ObjectError> errors = c.getBindingResult().getAllErrors(); StringBuilder errorMsg = new StringBuilder(); errors.forEach(x -> errorMsg.append(x.getDefaultMessage()).append(",")); } ... }} 或者在验证的类后面加 BindingResult,错误信息都会放在该对象里面,而不会抛出异常。如: 1234@PostMapping(value = "/login")public String login(@Validated LoginForm form, BindingResult bindingResult) {...}]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring MVC</tag>
</tags>
</entry>
<entry>
<title><![CDATA[从0开始手写一个Spring MVC框架,向高手进阶!]]></title>
<url>%2F2019%2F08%2F27%2F%E4%BB%8E0%E5%BC%80%E5%A7%8B%E6%89%8B%E5%86%99%E4%B8%80%E4%B8%AASpring-MVC%E6%A1%86%E6%9E%B6%EF%BC%8C%E5%90%91%E9%AB%98%E6%89%8B%E8%BF%9B%E9%98%B6%EF%BC%81%2F</url>
<content type="text"><![CDATA[从 0 开始手写一个 Spring MVC 框架,向高手进阶!Spring框架对于Java后端程序员来说再熟悉不过了,以前只知道它用的反射实现的,但了解之后才知道有很多巧妙的设计在里面。如果不看Spring的源码,你将会失去一次和大师学习的机会:它的代码规范,设计思想很值得学习。 我们程序员大部分人都是野路子,不懂什么叫代码规范。写了一个月的代码,最后还得其他老司机花3天时间重构,相信大部分老司机都很头疼看新手的代码。 废话不多说,我们进入今天的正题,在Web应用程序设计中,MVC模式已经被广泛使用。SpringMVC以DispatcherServlet为核心,负责协调和组织不同组件以完成请求处理并返回响应的工作,实现了MVC模式。点击这里学习 Spring MVC 常用注解。 想要实现自己的SpringMVC框架,需要从以下几点入手: 了解SpringMVC运行流程及九大组件 梳理自己的SpringMVC的设计思路 实现自己的SpringMVC框架 一、了解SpringMVC运行流程及九大组件1、SpringMVC的运行流程 ⑴ 用户发送请求至前端控制器DispatcherServlet ⑵ DispatcherServlet收到请求调用HandlerMapping处理器映射器。 ⑶ 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。 ⑷ DispatcherServlet通过HandlerAdapter处理器适配器调用处理器 ⑸ 执行处理器(Controller,也叫后端控制器)。 ⑹ Controller执行完成返回ModelAndView ⑺ HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet ⑻ DispatcherServlet将ModelAndView传给ViewReslover视图解析器 ⑼ ViewReslover解析后返回具体View ⑽ DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。 ⑾ DispatcherServlet响应用户。从上面可以看出,DispatcherServlet有接收请求,响应结果,转发等作用。有了DispatcherServlet之后,可以减少组件之间的耦合度。 2、SpringMVC的九大组件1234567891011121314151617181920protected void initStrategies(ApplicationContext context) { //用于处理上传请求。处理方法是将普通的request包装成 MultipartHttpServletRequest,后者可以直接调用getFile方法获取File. initMultipartResolver(context); //SpringMVC主要有两个地方用到了Locale:一是ViewResolver视图解析的时候;二是用到国际化资源或者主题的时候。 initLocaleResolver(context); //用于解析主题。SpringMVC中一个主题对应 一个properties文件,里面存放着跟当前主题相关的所有资源、//如图片、css样式等。SpringMVC的主题也支持国际化, initThemeResolver(context); //用来查找Handler的。 initHandlerMappings(context); //从名字上看,它就是一个适配器。Servlet需要的处理方法的结构却是固定的,都是以request和response为参数的方法。//如何让固定的Servlet处理方法调用灵活的Handler来进行处理呢?这就是HandlerAdapter要做的事情 initHandlerAdapters(context); //其它组件都是用来干活的。在干活的过程中难免会出现问题,出问题后怎么办呢?//这就需要有一个专门的角色对异常情况进行处理,在SpringMVC中就是HandlerExceptionResolver。 initHandlerExceptionResolvers(context); //有的Handler处理完后并没有设置View也没有设置ViewName,这时就需要从request获取ViewName了,//如何从request中获取ViewName就是RequestToViewNameTranslator要做的事情了。 initRequestToViewNameTranslator(context);//ViewResolver用来将String类型的视图名和Locale解析为View类型的视图。//View是用来渲染页面的,也就是将程序返回的参数填入模板里,生成html(也可能是其它类型)文件。 initViewResolvers(context); //用来管理FlashMap的,FlashMap主要用在redirect重定向中传递参数。 initFlashMapManager(context); } 二、梳理SpringMVC的设计思路本文只实现自己的@Controller、@RequestMapping、@RequestParam注解起作用,其余SpringMVC功能读者可以尝试自己实现。 1、读取配置 从图中可以看出,SpringMVC本质上是一个Servlet,这个 Servlet 继承自 HttpServlet。FrameworkServlet负责初始化SpringMVC的容器,并将Spring容器设置为父容器。因为本文只是实现SpringMVC,对于Spring容器不做过多讲解。点击这里学习 Spring MVC 常用注解。 为了读取web.xml中的配置,我们用到ServletConfig这个类,它代表当前Servlet在web.xml中的配置信息。通过web.xml中加载我们自己写的MyDispatcherServlet和读取配置文件。 2、初始化阶段在前面我们提到DispatcherServlet的initStrategies方法会初始化9大组件,但是这里将实现一些SpringMVC的最基本的组件而不是全部,按顺序包括: 加载配置文件 扫描用户配置包下面所有的类 拿到扫描到的类,通过反射机制,实例化。并且放到ioc容器中(Map的键值对 beanName-bean) beanName默认是首字母小写 初始化HandlerMapping,这里其实就是把url和method对应起来放在一个k-v的Map中,在运行阶段取出 3、运行阶段每一次请求将会调用doGet或doPost方法,所以统一运行阶段都放在doDispatch方法里处理,它会根据url请求去HandlerMapping中匹配到对应的Method,然后利用反射机制调用Controller中的url对应的方法,并得到结果返回。按顺序包括以下功能: 异常的拦截 获取请求传入的参数并处理参数 通过初始化好的handlerMapping中拿出url对应的方法名,反射调用。 三、实现自己的SpringMVC框架工程文件及目录: 首先,新建一个maven项目,在pom.xml中导入以下依赖: 12345678910111213141516171819202122<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.liugh</groupId> <artifactId>liughMVC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF- 8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> </dependencies></project> 接着,我们在WEB-INF下创建一个web.xml,如下配置: 1234567891011121314151617<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <servlet> <servlet-name>MySpringMVC</servlet-name> <servlet-class>com.liugh.servlet.MyDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>application.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MySpringMVC</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></web-app> application.properties文件中只是配置要扫描的包到SpringMVC容器中。 1scanPackage=com.liugh.core 创建自己的Controller注解,它只能标注在类上面: 12345678910111213141516171819package com.liugh.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface MyController { /** * 表示给controller注册别名 * @return */ String value() default "";} RequestMapping注解,可以在类和方法上: RequestParam注解,只能注解在参数上 12345678910111213141516171819package com.liugh.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface MyRequestParam { /** * 表示参数的别名,必填 * @return */ String value();} 然后创建MyDispatcherServlet这个类,去继承HttpServlet,重写init方法、doGet、doPost方法,以及加上我们第二步分析时要实现的功能: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245package com.liugh.servlet;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Method;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Properties;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.liugh.annotation.MyController;import com.liugh.annotation.MyRequestMapping;public class MyDispatcherServlet extends HttpServlet{private Properties properties = new Properties();private List<String> classNames = new ArrayList<>();private Map<String, Object> ioc = new HashMap<>();private Map<String, Method> handlerMapping = new HashMap<>();private Map<String, Object> controllerMap =new HashMap<>();@Overridepublic void init(ServletConfig config) throws ServletException { //1.加载配置文件 doLoadConfig(config.getInitParameter("contextConfigLocation")); //2.初始化所有相关联的类,扫描用户设定的包下面所有的类 doScanner(properties.getProperty("scanPackage")); //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v beanName-bean) beanName默认是首字母小写 doInstance(); //4.初始化HandlerMapping(将url和method对应上) initHandlerMapping(); }@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { //处理请求 doDispatch(req,resp); } catch (Exception e) { resp.getWriter().write("500!! Server Exception"); }}private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception { if(handlerMapping.isEmpty()){ return; } String url =req.getRequestURI(); String contextPath = req.getContextPath(); url=url.replace(contextPath, "").replaceAll("/+", "/"); if(!this.handlerMapping.containsKey(url)){ resp.getWriter().write("404 NOT FOUND!"); return; } Method method =this.handlerMapping.get(url); //获取方法的参数列表 Class<?>[] parameterTypes = method.getParameterTypes(); //获取请求的参数 Map<String, String[]> parameterMap = req.getParameterMap(); //保存参数值 Object [] paramValues= new Object[parameterTypes.length]; //方法的参数列表 for (int i = 0; i<parameterTypes.length; i++){ //根据参数名称,做某些处理 String requestParam = parameterTypes[i].getSimpleName(); if (requestParam.equals("HttpServletRequest")){ //参数类型已明确,这边强转类型 paramValues[i]=req; continue; } if (requestParam.equals("HttpServletResponse")){ paramValues[i]=resp; continue; } if(requestParam.equals("String")){ for (Entry<String, String[]> param : parameterMap.entrySet()) { String value =Arrays.toString(param.getValue()).replaceAll("\[|\]", "").replaceAll(",\s", ","); paramValues[i]=value; } } } //利用反射机制来调用 try { method.invoke(this.controllerMap.get(url), paramValues);//第一个参数是method所对应的实例 在ioc容器中 } catch (Exception e) { e.printStackTrace(); }}private void doLoadConfig(String location){ //把web.xml中的contextConfigLocation对应value值的文件加载到流里面 InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location); try { //用Properties文件加载文件里的内容 properties.load(resourceAsStream); } catch (IOException e) { e.printStackTrace(); }finally { //关流 if(null!=resourceAsStream){ try { resourceAsStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }private void doScanner(String packageName) { //把所有的.替换成/ URL url =this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\.", "/")); File dir = new File(url.getFile()); for (File file : dir.listFiles()) { if(file.isDirectory()){ //递归读取包 doScanner(packageName+"."+file.getName()); }else{ String className =packageName +"." +file.getName().replace(".class", ""); classNames.add(className); } }}private void doInstance() { if (classNames.isEmpty()) { return; } for (String className : classNames) { try { //把类搞出来,反射来实例化(只有加@MyController需要实例化) Class<?> clazz =Class.forName(className); if(clazz.isAnnotationPresent(MyController.class)){ ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance()); }else{ continue; } } catch (Exception e) { e.printStackTrace(); continue; } }}private void initHandlerMapping(){ if(ioc.isEmpty()){ return; } try { for (Entry<String, Object> entry: ioc.entrySet()) { Class<? extends Object> clazz = entry.getValue().getClass(); if(!clazz.isAnnotationPresent(MyController.class)){ continue; } //拼url时,是controller头的url拼上方法上的url String baseUrl =""; if(clazz.isAnnotationPresent(MyRequestMapping.class)){ MyRequestMapping annotation = clazz.getAnnotation(MyRequestMapping.class); baseUrl=annotation.value(); } Method[] methods = clazz.getMethods(); for (Method method : methods) { if(!method.isAnnotationPresent(MyRequestMapping.class)){ continue; } MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class); String url = annotation.value(); url =(baseUrl+"/"+url).replaceAll("/+", "/"); handlerMapping.put(url,method); controllerMap.put(url,clazz.newInstance()); System.out.println(url+","+method); } } } catch (Exception e) { e.printStackTrace(); } }/** * 把字符串的首字母小写 * @param name * @return */private String toLowerFirstWord(String name){ char[] charArray = name.toCharArray(); charArray[0] += 32; return String.valueOf(charArray);}} 这里我们就开发完了自己的SpringMVC,现在我们测试一下: 123456789101112131415161718192021222324252627282930313233343536package com.liugh.core.controller;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.liugh.annotation.MyController;import com.liugh.annotation.MyRequestMapping;import com.liugh.annotation.MyRequestParam;@MyController@MyRequestMapping("/test")public class TestController { @MyRequestMapping("/doTest") public void test1(HttpServletRequest request, HttpServletResponse response, @MyRequestParam("param") String param){ System.out.println(param); try { response.getWriter().write( "doTest method success! param:"+param); } catch (IOException e) { e.printStackTrace(); } } @MyRequestMapping("/doTest2") public void test2(HttpServletRequest request, HttpServletResponse response){ try { response.getWriter().println("doTest2 method success!"); } catch (IOException e) { e.printStackTrace(); } }} 访问 http://localhost:8080/liughMVC/test/doTest?param=liugh如下: 访问一个不存在的试试: 到这里我们就大功告成了!水平有限,文章难免有错误,欢迎牺牲自己宝贵时间的读者,就本文内容直抒己见,我的目的仅仅是希望对读者有所帮助。 源码地址:/github.com/qq53182347/liughMVC]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring MVC</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring MVC表单防止重复提交]]></title>
<url>%2F2019%2F08%2F27%2FSpring-MVC%E8%A1%A8%E5%8D%95%E9%98%B2%E6%AD%A2%E9%87%8D%E5%A4%8D%E6%8F%90%E4%BA%A4%2F</url>
<content type="text"><![CDATA[Spring MVC表单防重复提交利用Spring MVC的过滤器及token传递验证来实现表单防重复提交。 创建注解1234567@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Token { boolean create() default false; boolean remove() default false;} 在跳转页面的方法上加上:@Token(create = true)\ 在提交的action方法上加上:@Token(remove = true) 创建过滤器123456789101112131415161718192021222324252627282930313233343536373839404142434445public class TokenInterceptor extends HandlerInterceptorAdapter { private Logger logger = Logger.getLogger(TokenInterceptor.class); private static final String TOKEN = "token"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { Method method = ((HandlerMethod) handler).getMethod(); Token annotation = method.getAnnotation(Token.class); if (annotation != null) { HttpSession session = request.getSession(); // 创建token boolean create = annotation.create(); if (create) { session.setAttribute(TOKEN, UUID.randomUUID().toString()); return true; } // 删除token boolean remove = annotation.remove(); if (remove) { if (isRepeatSubmit(request)) { logger.warn("表单不能重复提交:" + request.getRequestURL()); return false; } session.removeAttribute(TOKEN); } } } else { return super.preHandle(request, response, handler); } return true; } private boolean isRepeatSubmit(HttpServletRequest request) { String token = (String) request.getSession().getAttribute(TOKEN); if (token == null) { return true; } String reqToken = request.getParameter(TOKEN); if (reqToken == null) { return true; } if (!token.equals(reqToken)) { return true; } return false; } } 配置拦截器123456<!--配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.example.web.interceptor.TokenInterceptor"/> </mvc:interceptor></mvc:interceptors> 表单添加token1<input type="hidden" id="token" name="token" value="$!{session.getAttribute('token')}"/> 在form表单里面添加token域,提交表单时需要传过去。]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring MVC</tag>
</tags>
</entry>
<entry>
<title><![CDATA[@Controller,@Service,@Component详解]]></title>
<url>%2F2019%2F08%2F27%2FController-Service-Component%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[@Controller,@Service,@Repository,@Component详解。@Controller 用来表示一个web控制层bean,如SpringMvc中的控制器。 @Service 用来表示一个业务层bean。 @Repository 用来表示一个持久层bean,即数据访问层DAO组件。 @Component 用来表示一个平常的普通组件,当一个类不合适用以上的注解定义时用这个组件修饰。 需要注意的是@Controller,@Service,@Repository都有带@Component父注解,说明它们除了基本组件的属性外还有其他的的场景应用,即如果不用SpringMVC其实它们就是一个普通的组件,但普通组件建议最好还是用@Component修饰。 为了让Spring自动扫描注册这些组件,需要在配置文件中加上扫描的配置,如扫描com.test包下的注解。 <context:component-scan base-package=”com.test” /> 些扫描配置默认use-default-filters=”true”,默认扫描@Component注解及子注解,可以配置过滤只扫描哪些注解不扫描哪些注解。 要过滤扫描注解,需要相应的带上下面的子标签,可以有多个。 context:include-filter context:exclude-filter 如只扫描com.test包下的@Controller和@Service注解的组件。 <context:component-scan base-package=”com.test” use-default-filters=”false”> <context:include-filter type=”annotation” expression=”org.springframework.stereotype.Controller”/> <context:include-filter type=”annotation” expression=”org.springframework.stereotype.Service”/> 关于type的定义 Filter Type Examples Expression Description annotation org.example.SomeAnnotation 符合SomeAnnoation的target class assignable org.example.SomeClass 指定class或interface的全名 aspectj org.example..*Service+ AspectJ语法 regex org.example.Default.* Regelar Expression custom org.example.MyTypeFilter 自定义Type,实现接口org.springframework.core.type.TypeFilter 另外,context:component-scan配置可以有多个。]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring MVC</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring MVC常用注解,你会几个]]></title>
<url>%2F2019%2F08%2F27%2FSpring-MVC%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3%EF%BC%8C%E4%BD%A0%E4%BC%9A%E5%87%A0%E4%B8%AA%2F</url>
<content type="text"><![CDATA[常用注解 Controller 注解一个类表示控制器,Spring MVC会自动扫描标注了这个注解的类。 RequestMapping 请求路径映射,可以标注类,也可以是方法,可以指定请求类型,默认不指定为全部接收。 RequestParam 放在参数前,表示只能接收参数a=b格式的数据,即 Content-Type为 application/x-www-form-urlencoded类型的内容。 RequestBody 放在参数前,表示参数从request body中获取,而不是从地址栏获取,所以这肯定是接收一个POST请求的非a=b格式的数据,即 Content-Type不为 application/x-www-form-urlencoded类型的内容。 ResponseBody 放在方法上或者返回类型前,表示此方法返回的数据放在response body里面,而不是跳转页面。一般用于ajax请求,返回json数据。 RestController 这个是Controller和ResponseBody的组合注解,表示@Controller标识的类里面的所有返回参数都放在response body里面。 PathVariable 路径绑定变量,用于绑定restful路径上的变量。 @RequestHeader 放在方法参数前,用来获取request header中的参数值。 @CookieValue; 放在方法参数前,用来获取request header cookie中的参数值。 GetMapping PostMapping PutMapping.. *Mapping的是Spring4.3加入的新注解,表示特定的请求类型路径映射,而不需要写RequestMethod来指定请求类型。 演示12345678910111213141516171819import org.dom4j.util.UserDataElement;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/test") public class TestController { @RequestMapping(value = "/get/{no}", method = RequestMethod.GET) @ResponseBody public Object get(@PathVariable("no") String no) { return new UserDataElement(""); } @RequestMapping(value = "/save", method = RequestMethod.POST) public void save(@RequestBody UserDataElement user) { } }]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring MVC</tag>
</tags>
</entry>
<entry>
<title><![CDATA[MyBatis第2天]]></title>
<url>%2F2019%2F08%2F26%2FMyBatis%E7%AC%AC2%E5%A4%A9%2F</url>
<content type="text"><![CDATA[1关联查询1.1 案例:用户和定单 Ø user和orders:User 与orders:一个用户可以创建多个订单,一对多Orders 与 user:多个订单只由一个用户创建,多对一Ø orders**和orderdetail:Orders 与 orderdetail:一个订单可以包括 多个订单明细,因为一个订单可以购买多个商品,每个商品的购买信息在orderdetail记录,一对多关系orderdetail 与orders:多个订单明细包括在一个订单中, 多对一Ø** orderdetail**和items:**Orderdetail 与 items:多个订单明细只对应一个商品信息,多对一Items 与 orderdetail:一个商品可以包括在多个订单明细 ,一对多 需求:根据**商品ID查找定单信息,包括用户名和地址** #查找id为10的所有定单SELECT orders.id, orders.number,orders.createtime,orders.note,user.username,user.addressFROM orders ,user WHERE orders.user_id = user.id AND user.id = 10; 1.2 一对一 resultType实现复杂查询时,单表对应的po类已不能满足输出结果集的映射。所以要根据需求建立一个扩展类来作为resultType的类型。 #查找某个定单id的信息,包括用户名字和地址SELECT o.*,u.username,u.address FROM orders o,user uWHERE o.user_id = u.id AND o.id = 3 第一步:写个定单的扩展类 第二步:声明定单接口 第三步:声明定单配置文件 第四步:**加载映射文件** 第五步:测试 一对一 resultMap实现掌握association的使用 OrdersMapper.java添加一个方法 OrdersMapper.xml 测试 总结resultType:使用resultType实现较为简单,如果pojo中没有包括查询出来的列名,需要增加列名对应的属性,即可完成映射。如果没有查询结果的特殊要求建议使用resultType。 resultMap:需要单独定义resultMap,实现有点麻烦,如果对查询结果有特殊的要求,使用resultMap可以完成将关联查询映射pojo的对象属性中。 resultMap可以实现延迟加载,resultType无法实现延迟加载。 1.3 一对多需求:根据定单ID查找定单信息、用户信息和定单明细信息 Select orders.id, orders.user_id, orders.number, orders.createtime, orders.note, user.username, user.address, orderdetail.id detail_id, orderdetail.items_id, orderdetail.items_num from orders,user,orderdetail where orders.user_id = user.id and orders.id = orderdetail.orders_id and orders.id = #{?}; SELECT o.*, u.username, u.address, od.id detail_id, od.items_id, od.items_numFROM orders o, user u, orderdetail odWHERE o.user_id = u.id AND o.id = od.orders_id AND o.id = 3 目标:掌握collection的使用 第一步:在Orders中添加定单明细 第二步:Mapper接口 第三步:OrderMapper.xmlresultMap中有个extends属性,可以继承【自行研究】 第四步:测试 总结mybatis使用resultMap的collection对关联查询的多条记录映射到一个list集合属性中。 使用resultType实现: 需要对结果集进行二次处理。 将订单明细映射到orders中的orderdetails中,需要自己处理,使用双重循环遍历,去掉重复记录,将订单明细放在orderdetails中。 1.4 多对多需求查询用户信息及用户购买的商品信息,要求将关联信息映射到主pojo的pojo属性中 Sql Select user.id, user.username, user.address, orders.id orders_id, orders.user_id, orders.number, orders.createtime, orders.note, orderdetail.id detail_id, orderdetail.items_id, orderdetail.items_num, items.name items_name, items.detail items_detail FROM USER,orders,orderdetail,items WHERE user.id = orders.user_id AND orders.id = orderdetail.orders_id AND orderdetail.items_id = items.id SELECT u.id, u.username, u.address, o.id order_id, o.number, o.createtime, o.note, od.id detail_id, od.items_id, od.items_num, it.name, it.price, it.detailFROM user u, orders o, orderdetail od, items itWHERE o.user_id = u.id AND o.id = od.orders_id AND od.items_id = it.id; 映射思路v 将用户信息映射到user中。 v 在user类中添加订单列表属性List orderslist,将用户创建的订单映射到orderslist v 在Orders中添加订单明细列表属性List detailList,将订单的明细映射到detailList v 在Orderdetail中添加Items属性,将订单明细所对应的商品映射到Items 第一步:UserMapper.java 第二步:User/Orders/Orderdetail.java 第三步:UserMapper.xml 第四步:测试 打印效果 总结resultType:将查询结果按照sql列名pojo属性名一致性映射到pojo中。 resultMap:使用association和collection完成一对一和一对多高级映射(对结果有特殊的映射要求)。 association:将关联查询信息映射到一个pojo对象中。 collection:将关联查询信息映射到一个list集合中。 2 延时加载2.1 延迟加载延迟加载又叫懒加载,也叫按需加载。也就是说先加载主信息,在需要的时候,再去加载从信息。 在mybatis中,resultMap标签 的association标签和collection标签具有延迟加载的功能。 2.1 案例:Mapper.java Mapper.xml UserMappler.xml OrdersMapper.xml 测试 配置懒加载 3查询缓存3.1 M**ybatis的缓存理解**Mybatis的缓存,包括一级缓存和二级缓存,一级缓存是默认使用的。二级缓存需要手动开启。 一级缓存指的就是sqlsession,在sqlsession中有一个数据区域,是map结构,这个区域就是一级缓存区域。一级缓存中的key是由sql语句、条件、statement等信息组成一个唯一值。一级缓存中的value,就是查询出的结果对象。 二级缓存指的就是同一个namespace下的mapper,二级缓存中,也有一个map结构,这个区域就是一级缓存区域。一级缓存中的key是由sql语句、条件、statement等信息组成一个唯一值。一级缓存中的value,就是查询出的结果对象。 3.2 一级缓存原理: 测试1 测试2 3.3 二级缓存原理: 使用:开启二级缓存**总开关** UserMapper中配置二级缓存 User系列化 测试 禁用**指定方法二级**缓存 刷新缓存 3.4 整合**ehcache**Mybatis本身是一个持久层框架,它不是专门的缓存框架,所以它对缓存的实现不够好,不能支持分布式。 Ehcache是一个分布式的缓存框架。 什么是分布式系统为了提高性能,通常会对系统采用分布式部署(集群部署方式) 整合思路Cache是一个接口,它的默认实现是mybatis的PerpetualCache。如果想整合mybatis的二级缓存,那么实现Cache接口即可。 添加jar包 设置映射文件中cache标签的type值为ehcache的实现类 在src下**添加ehcache的配置文件** Ø maxElementsInMemory :设置基于内存的缓存中可存放的对象最大数目 Ø eternal:设置对象是否为永久的,true表示永不过期,此时将忽略Ø timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false Ø timeToIdleSeconds:设置对象空闲最长时间,以秒为单位, 超过这个时间,对象过期。当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态。 Ø timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。如果此值为0,表示对象可以无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值 Ø overflowToDisk:设置基于内在的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中 Ø diskPersistent 当jvm结束时是否持久化对象 true false 默认是falseØ diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出) 测试:用上面二级缓存例子即可二级缓存**应用场景**使用场景:对于访问响应速度要求高,但是实时性不高的查询,可以采用二级缓存技术。 注意:在使用二级缓存的时候,要设置一下刷新间隔(cache标签中有一个flashInterval属性)来定时刷新二级缓存,这个刷新间隔根据具体需求来设置,比如设置30分钟、60分钟等,单位为毫秒。 局限性M**ybatis二级缓存对细粒度的数据,缓存实现不好。** 场景: 对商品信息进行缓存,由于商品信息查询访问量大,但是要求用户每次查询都是最新的商品信息,此时如果使用二级缓存,就无法实现当一个商品发生变化只刷新该商品的缓存信息而不刷新其他商品缓存信息,因为二级缓存是mapper级别的,当一个商品的信息发送更新,所有的商品信息缓存数据都会清空。 解决此类问题,需要在业务层根据需要对数据有针对性的缓存。 比如可以对经常变化的 数据操作单独放到另一个namespace的mapper中。 4. mybaties整合springSSH:struts2+spring+hibernate SSM:SpringMVC + Spring + MyBatis Spring 3.2 Mybaties 3.2.7 4.1 创建工程导包导入mybaties包 mybaties核心包 mybatis依赖包 导入mysql数据库驱动 数据库dbcp连接池 导入spring+mvc包 Mybatis-spring整合包 4.2 配置mybatis的核心配置文件核心配置文件、创建User模型、映射文件, 4.3 spring的数据源<beans xmlns=*”http://www.springframework.org/schema/beans"* xmlns:xsi=*”http://www.w3.org/2001/XMLSchema-instance"* xmlns:mvc=*”http://www.springframework.org/schema/mvc"* xmlns:context=*”http://www.springframework.org/schema/context"* xmlns:aop=*”http://www.springframework.org/schema/aop"* xmlns:tx=*”http://www.springframework.org/schema/tx"* xsi:schemaLocation=*”http://www.springframework.org/schema/beans* http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd “> <bean id=*”datasourse”* class=*”org.apache.commons.dbcp.BasicDataSource”> <property name=“driverClassName”* value=*”xxx“/> <property name=“url”* value=*”xxx“/> <property name=“username”* value=*”xxx/> <property name=“password”* value=*”xxx*”/> <property name=*”maxActive”* value=*”10”/> <property name=“maxIdle”* value=*”5”*/> 4.4 spring配置SqlSessionFactory 4.5 编写个UserDaoImpl,接口省略 4.6 spring中配置daobean 4.7测试 4.8 换成Mapper接口整合dao创建Mapper映射文件 UserMapper UserMapper.xml 核心配置文件加载映射文件 Spring配置MapperFactoryBean使用工厂Bean生成userMapper对象 测试 用**MapperScannerConfigurer批量扫描创建代理对象**【上面的代码麻烦,每一个mappler就创建一个工厂bean】 测试与上一个测试一样 5. 逆向工程简介简单点说**,就是通过数据库中的单表,自动生成java代码**。 Mybatis官方提供了逆向工程 可以针对单表自动生成mybatis代码(mapper.java\mapper.xml\po类) 企业开发中,逆向工程是个很常用的工具。 下载逆向工程https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.3.2 使用方法1、 创建简单的java项目 2、 导入jar包,创建generator配置文件; 3、 使用java类来执行逆向工程; 4、 把生成的代码拷贝到项目中。 5、 在正式项目中使用逆向工程生成的代码 第一步**:创建generator配置文件**在classpath下,创建generator.xml配置文件:(文件内容可以从逆向工程的jar包中docs目录下的index.html中找到相关代码) <context id=*”mysqlTable”* targetRuntime=*”MyBatis3”> <jdbcConnection driverClass=“com.mysql.jdbc.Driver”* connectionURL=*”jdbc:mysql://localhost:3306/mybatis”* userId=*”root”* password=*”123456”> <property name=“forceBigDecimals”* value=*”false”* /> <javaModelGenerator targetPackage=*”com.gyf.backoffice.domain”* targetProject=*”.\src”> <property name=“enableSubPackages”* value=*”true”* /> <property name=*”trimStrings”* value=*”true”* /> <sqlMapGenerator targetPackage=*”com.gyf.backoffice.mapper”* targetProject=*”.\src”> <property name=“enableSubPackages”* value=*”true”* /> <javaClientGenerator type=*”XMLMAPPER”* targetPackage=*”com.gyf.backoffice.mapper”* targetProject=*”.\src”> <property name=“enableSubPackages”* value=*”true”* /> <table tableName=*”items”/> <table tableName=“orderdetail”/> <table tableName=“orders”/> <table tableName=“user”*/> 第二步:使用java类来执行逆向工程需要导入mysql的驱动包和mybatis的逆向工程包 public class Generator { public static void main(String[] args) throws Exception{ List warnings = new ArrayList(); boolean overwrite = true; File configFile = new File(“config/generator.xml”); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); }} 第三步:**把生成的代码拷贝到项目中**如果正式项目中已经有po类所在的包了,那么就只需要拷贝po类到指定包下就可以。 如果正式项目中没有po包,那么就把逆向工程中整个po类的包拷贝过去。 Mapper.xml和mapper.java的拷贝与po类一样。 第四步:测试逆向工程提供了很多查询方法,可以不用写sql,这个根hibernate有点类似]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>MyBatis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[MyBatis第1天]]></title>
<url>%2F2019%2F08%2F26%2FMyBatis%E7%AC%AC1%E5%A4%A9%2F</url>
<content type="text"><![CDATA[1 MyBatis简介1.1 MyBatisMyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。 MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。 对jdbc的封装框架有哪些:Hibernate,dbutils,jdbcTemplate[spring],mybatis 原理:Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。 1.2 jdbc程序代码 存在的问题 v 数据库连接频繁开启和关闭,会严重影响数据库的性能。 v 代码中存在硬编码,分别是数据库部分的硬编码和SQL执行部分的硬编码。 1.3 MyBatis的框架核心1、 mybatis配置文件,包括M**ybatis全局配置文件和**Mybatis映射文件,其中全局配置文件配置了数据源、事务等信息;映射文件配置了SQL执行相关的 信息。2、 mybatis通过读取配置文件信息(全局配置文件和映射文件),构造出SqlSessionFactory**,即会话工厂。3、 通过SqlSessionFactory,可以创建SqlSession即会话。Mybatis是通过SqlSession来操作数据库的。4、 SqlSession本身不能直接操作数据库,它是通过底层的Executor执行器接口来操作数据库的。Executor接口有两个实现类,一个是普通执行器,一个是缓存执行器(默认)。5、 Executor执行器要处理的SQL信息是封装到一个底层对象MappedStatement中。该对象包括:SQL语句、输入参数映射信息、输出结果集映射信息。其中输入参数和输出结果的映射类型包括HashMap集合对象、POJO对象类型**。 2 Mybatis入门2.1 环境准备创建数据库表 下载MyBatismybaits的代码由github.com管理,下载地址:https://github.com/mybatis/mybatis-3/releases 创建项目导包导入下面的包 添加log4j.propertiesMybatis使用的日志包是log4j的,所以需要添加log4j.properties。 在classpath下创建log4j.properties如下:【文件内容可以从mybatis-3.2.7.pdf中拷贝】 # Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output… log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 日志级别在开发阶段设置成DEBUG,在生产阶段设置成INFO或者ERROR。 2.2 开发步骤1、 创建PO(model)类,根据需求创建;2、 创建全局配置文件SqlMapConfig.xml;3、 编写映射文件;4、 加载映射文件,在SqlMapConfig.xml中进行加载;5、 编写测试程序,即编写Java代码,连接并操作数据库。 思路:a) 读取配置文件;b) 通过SqlSessionFactoryBuilder创建SqlSessionFactory会话工厂。c) 通过SqlSessionFactory创建SqlSession。d) 调用SqlSession的操作数据库方法。e) 关闭SqlSession。 创建PO类 创建SqlMapConfig.xml在classpath(src)下,创建SqlMapConfig.xml文件【SqlMapConfig.xml(文件头可以从mybatis-3.2.7.pdf文档的2.1.2小节中拷贝)】 <environments default=*”development”> <environment id=“development”> <transactionManager type=“JDBC”> <dataSource type=“POOLED”> <property name=“driver”* value=*”com.mysql.jdbc.Driver”/> <property name=“url”* value=*”jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8”/> <property name=“username”* value=*”root”/> <property name=“password”* value=*”123456”*/> 映射文件在classpath下,创建sqlmap文件夹。在sqlmap目录下,创建User.xml映射文件。 【Mybatis的映射文件头(可以从mybatis-3.2.7.pdf文件中拷贝)】 SELECT * FROM USER WHERE id = #{id} 配置文件加载映射文件 测试类 2.3 更多案例讲解模糊查询用户信息 <select id=*”findUserByName”* parameterType=*”String”* resultType=*”com.gyf.domain.User”*> SELECT * FROM USER WHERE username like ‘%${value}%’ 插入用户信息 删除用户 更新用户 主键返回之MySQL自增主键思路: Ø MySQL自增主键,是指在insert之前MySQL会自动生成一个自增的主键。 Ø 我们可以通过MySQL的函数获取到刚插入的自增主键: LAST_INSERT_ID() Ø 这个函数是在insert语句之后去调用。 <insert id=*”insertUser”* parameterType=*”com.gyf.domain.User”> <selectKey keyProperty=“id”* resultType=*”int”* order=*”AFTER”*> SELECT LAST_INSERT_ID() INSERT INTO USER (username,sex,birthday,address) VALUES(#{username},#{sex},#{birthday},#{address}) 主键返回之MySQL自增**UUID**<insert id=*”insertUser”* parameterType=*”com.gyf.domain.User”> <selectKey keyProperty=“id”* resultType=*”String“* order=*”BEFORE“*> SELECT UUID() INSERT INTO USER (username,sex,birthday,address) VALUES(#{username},#{sex},#{birthday},#{address}) ORCLE主键SELECT user_seq.nextval() FROM dual 小结:parameterType和**resultTypeparameterType指定输入参数的java类型,可以填写别名或Java类的全限定名。resultType指定输出结果的java类型,可以填写别名或Java类的全限定名。 #{}和**${}#{}:相当于预处理中的占位符?。#{}里面的参数表示接收java输入参数的名称。#{}可以接受HashMap、POJO类型的参数。当接受简单类型的参数时,#{}里面可以是value,也可以是其他。#{}可以防止SQL注入。${}:相当于拼接SQL串,对传入的值不做任何解释的原样输出。${}会引起SQL注入,所以要谨慎使用。${}可以接受HashMap、POJO类型的参数。当接受简单类型的参数时,${}里面只能是value。 selectOne和selectListselectOne:只能查询0或1条记录,大于1条记录的话,会报错:selectList:可以查询0或N条记录 2.4 MyBatis的Dao编写 【一般不用,有更多好方式】dao 测试 2.5 MyBatis的Dao编写【mapper代理方式实现】Mapper代理的开发方式,程序员只需要编写mapper接口(相当于dao接口)即可。Mybatis会自动的为mapper接口生成动态代理实现类。 不过要实现mapper代理的开发方式,需要遵循一些开发规范。 开发规范 mapper接口的全限定名要和mapper映射文件的namespace的值相同。2. mapper接口的方法名称要和mapper映射文件中的statement的id相同;3. mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。4. mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致; 通过规范式的开发mapper接口,可以解决原始dao开发当中存在的问题:l 模板代码已经去掉;l 剩下去不掉的操作数据库的代码,其实就是一行代码。这行代码中硬编码的部分,通过第一和第二个规范就可以解决。 编写步骤第一步:【】重新写个UserMapper配置文件和定义mapper映射文件UserMapper.xml(内容同Users.xml,除了namespace的值),放到新创建的目录mapper下。 第二步:【添加映射配置文件】 第三步:测试 3 全局配置文件其它配置3.1 properties数据库文件配置在src下配置个db.properties文件 修改全局的配置文件 3.2 setting【了解】 具体配置详解 3.3 typeAliases别名是使用是为了在映射文件中,更方便的去指定参数和结果集的类型,不再用写很长的一段全限定名。 mybatis支持的别名 别名 映射的类型 _byte byte _long long _short short _int int _integer int _double double _float float _boolean boolean string String byte Byte long Long short Short int Integer integer Integer double Double float Float boolean Boolean date Date decimal BigDecimal bigdecimal BigDecimal 自定义别名 mappers<mapper resource=’’/>使用相对于类路径的资源 如: 【不用】使用完全限定路径 如: 使用mapper接口的全限定名 如: 也可使用注解开发,把xml文件删除 注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下; (推荐)注册指定包下的所有映射文件 如: 注意**:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下**; 4 Mybatis的映射文件4.1 输入映射ParameterType指定输入参数的java类型,可以使用别名或者类的全限定名。它可以接收简单类型**,POJO对象**、HashMap。 传递简单类型根据用户ID查询用户信息。 传递POJO对象 传递POJO包装对象开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。 需求 综合查询用户信息,需要传入查询条件复杂,比如(用户信息、订单信息、商品信息)。 vo:键值对对象,相对于kv po:persist object 持久化对象 pojo:简单的java对象 entity:实体 定义POJO包装类 修改UserMapper.java 修改UsrMappler.xml 测试 传递Map对象 修改UserMapper.java 修改UserMapper.xml 测试 4.2 输出映射 resultType/resultMapresultType使用resultType进行结果映射时,查询的列名和映射的pojo属性名完全一致,该列才能映射成功。 如果查询的列名和映射的pojo属性名全部不一致,则不会创建pojo对象; 如果查询的列名和映射的pojo属性名有一个一致,就会创建pojo对象。 输出简单类型当输出结果只有一列时,可以使用ResultType指定简单类型作为输出结果类型。 案例:输出一个count(*) UserMapper.java UserMapper.xml 测试 输出POJO单个对象 输出POJO列表 总结: 输出单个pojo对象和pojo列表时,mapper映射文件中的resultType的类型是一样的,mapper接口的方法返回值不同。 同样的mapper映射文件,返回单个对象和对象列表时,mapper接口在生成动态代理的时候,会根据返回值的类型,决定调用selectOne方法还是selectList方法。 resultMap如果查询出来的列名和属性名不一致,通过定义一个resultMap将列名和pojo属性名之间作一个映射关系。 1、 定义resultMap 2、使用resultMap作为statement的输出映射类型 UserMapper.java UserMapper.xml 测试 5 动态SQL5.1 if和whereØ If标签:作为判断入参来使用的,如果符合条件,则把if标签体内的SQL拼接上。 注意**:用if进行判断是否为空时,不仅要判断null,也要判断空字符串‘’;** Ø Where标签:会去掉条件中的第一个and符号。 5.2 SQL片断Mybatis提供了SQL片段的功能,可以提高SQL的可重用性。 5.3 foreach 遍历案例:查询指定id的用户【SELECT * FROM user where id in (31,32,33); 】 UserQueryVO.java UserMapper.xml 测试: 另一种遍历,参数直接传入id集合【自己练】 6 mybatis与hibernate的区别【面试题】Mybatis技术特点:好处: 通过直接编写SQL语句,可以直接对SQL进行性能的优化; 学习门槛低,学习成本低。只要有SQL基础,就可以学习mybatis,而且很容易上手; 由于直接编写SQL语句,所以灵活多变,代码维护性更好。 缺点: 不能支持数据库无关性,即数据库发生变更,要写多套代码进行支持,移植性不好。 Mysql:limit Oracle:rownum 需要编写结果映射。 Hibernate技术特点:好处: 标准的orm框架,程序员不需要编写SQL语句。 具有良好的数据库无关性,即数据库发生变化的话,代码无需再次编写。 以后,mysql数据迁移到oracle,只需要改方言配置 缺点: 学习门槛高,需要对数据关系模型有良好的基础,而且在设置OR映射的时候,需要考虑好性能和对象模型的权衡。 程序员不能自主的去进行SQL性能优化。 Mybatis应用场景:需求多变的互联网项目,例如电商项目。 Hibernate.应用场景:需求明确、业务固定的项目,例如OA项目、ERP项目等。]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>MyBatis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring第3天]]></title>
<url>%2F2019%2F08%2F26%2FSpring%E7%AC%AC3%E5%A4%A9%2F</url>
<content type="text"><![CDATA[1 事务管理1.1 事务回顾事务简介一组业务ABCD操作,要么全部成功,要么全部不成功。 事务特性:ACIDØ 原子性:整体 【原子性是指事务包含的所有操作要么全部成功,要么全部失败】 Ø 一致性:数据 【一个事务执行之前和执行之后都必须处于一致性状态】 Ø 隔离性:并发 【对于任意两个并发的事务T1和T2,在事务T1看来,T2要么在T1开始之前就已经结束,要么在T1结束之后才开始,这样每个事务都感觉不到有其他事务在并发地执行。】 Ø 持久性:结果 【持久性是指一个事务一旦被提交了,那么对数据库中的数据的改变就是永久性的】 隔离问题Ø 脏读:一个事务读到另一个事务未提交的内容【读取未提交内容】 在该隔离级别,所有事务都可以看到其他未提交事务的执行结果。本隔离级别很少用于实际应用,因为它的性能也不比其他级别好多少。 Ø 不可重复读:一个事务读到另一个事务已提交的内容(insert)【读取提交内容】 这是大多数数据库系统的默认隔离级别(但不是MySQL默认的)。它满足了隔离的简单定义:一个事务只能看见已经提交事务所做的改变。 Ø 虚读(幻读):一个事务读到另一个事务已提交的内容(update) 这是MySQL的默认事务隔离级别,它确保同一事务的多个实例在并发读取数据时,会看到同样的数据行。不过理论上,这会导致另一个棘手的问题:幻读 (Phantom Read)。简单的说,幻读指当用户读取某一范围的数据行时,另一个事务又在该范围内插入了新行,当用户再读取该范围的数据行时,会发现有新的“幻影” 行。 Ø Serializable(可串行化) 这是最高的隔离级别,它通过强制事务排序,使之不可能相互冲突,从而解决幻读问题。简言之,它是在每个读的数据行上加上共享锁。在这个级别,可能导致大量的超时现象和锁竞争。 隔离级别–解决问题Ø read uncommittd,读未提交。存在3个问题。 Ø read committed,读已提交。解决:脏读。存在2个问题。 Ø repeatable read ,可重复读。解决:脏读、不可重复读。存在1个问题。 Ø serializable,串行化。单事务。没有问题。 mysql 事务操作–简单ABCD 一个事务Connection conn = null;try{ //1 获得连接 conn = …; //2 开启事务 conn.setAutoCommit(false); A B C D //3 提交事务 conn.commit();} catche(){ //4 回滚事务 conn.rollback();} mysql 事务操作–Savepoint需求:AB(必须),CD(可选) Connection conn = null;Savepoint savepoint = null; //保存点,记录操作的当前位置,之后可以回滚到指定的位置。(可以回滚一部分)try{ //1 获得连接 conn = …; //2 开启事务 conn.setAutoCommit(false); A B savepoint = conn.setSavepoint(); C D //3 提交事务 conn.commit();} catche(){ if(savepoint != null){ //CD异常 // 回滚到CD之前 conn.rollback(savepoint); // 提交AB conn.commit(); } else{ //AB异常 // 回滚AB conn.rollback(); }} 1.2 Spring事务管理介绍1.2.1 Spring提供的事务jar包transaction = tx 1.2.2 Jar中的三个顶级接口 PlatformTransactionManager**:平台事务管理器,spring要管理事务,必须使用事务管理器,进行事务配置时,必须配置事务管理器** TransactionDefinition:事务详情(事务定义、事务属性),spring用于确定事务具体详情,例如:隔离级别、是否只读、超时时间 等进行事务配置时,必须配置详情。spring将配置项封装到该对象实例。 TransactionStatus:事务状态,spring用于记录当前事务运行状态。例如:是否有保存点,事务是否完成。spring底层根据状态进行相应操作。 1.2.3 PlatformTransactionManager 事务管理器先导入两个包 常用的两个事务管理器 1.2.4 TransactionStatus 事务状态 1.2.5 TransactionDefinition 传播行为:在两个业务之间如何共享事务 PROPAGATION_REQUIREDrequired , 必须 【默认值】 支持当前事务,A如果有事务,B将使用该事务。如果A没有事务,B将创建一个新的事务。 PROPAGATION_SUPPORTSsupports ,支持 支持当前事务,A如果有事务,B将使用该事务。如果A没有事务,B将以非事务执行。 PROPAGATION_MANDATORYmandatory ,强制 支持当前事务,A如果有事务,B将使用该事务。如果A没有事务,B将抛异常。 PROPAGATION_REQUIRES_NEW requires_new ,必须新的 如果A有事务,将A的事务挂起,B创建一个新的事务如果A没有事务,B创建一个新的事务 PROPAGATION_NOT_SUPPORTEDnot_supported ,不支持 如果A有事务,将A的事务挂起,B将以非事务执行如果A没有事务,B将以非事务执行 PROPAGATION_NEVERnever,从不 如果A有事务,B将抛异常如果A没有事务,B将以非事务执行 PROPAGATION_NESTEDnested ,嵌套 A和B底层采用保存点机制,形成嵌套事务。 掌握:PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED 1.3 案例:转帐 1.3.1 环境搭建创建数据库表create database spring_day3;use spring_day3;create table account( id int primary key auto_increment, username varchar(50), money int);insert into account(username,money) values(‘jack’,’10000’);insert into account(username,money) values(‘rose’,’10000’); 导入jar包l 核心:4+1 l aop : 4 (aop联盟、spring aop、aspectj规范、spring aspect) l 数据库:2 (jdbc/tx) l 驱动:mysql l 连接池:c3p0 Dao层 Service层 Spring的配置配置c3p0数据源->dao -> service 测试转帐 1.3.2 手动管理事务【了解】spring底层使用 TransactionTemplate 事务模板进行操作。 操作 1.service 需要获得 TransactionTemplate 2.spring 配置模板,并注入给service 3.模板需要注入事务管理器 4.配置事务管理器:DataSourceTransactionManager ,需要注入DataSource 了解底层即可,因为以后都是通过aop来配置事务 修改Service 修改spring的配置文件 1.3.3 工厂bean生成代理:半自动Spring提供 管理事务的代理工厂bean TransactionProxyFactoryBean 修改spring配置文件transactionAttributes:事务详情prop.key :确定哪些方法使用当前事务配置 prop.text:用于配置事务详情 格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception 传播行为 隔离级别 是否只读 异常回滚 异常提交 测试: 1.3.4 基本AOP的事务配置【掌握】Spring的配置文件 测试同上1.3.5 基本于注解的事务spring配置 1.3.5 整合Junit目的:少写一些代码 导入一个spring-test包 2. SSH整合2.1 web 整合spring配置tomcat加载spring的配置文件 第一步:需要添加 第二步:在web.xml配置spring的监听 出现下面的错误是配置文件加载位置不对,在web.xml改成classpath目录下 第三步:创建Servlet获取Spring的应用上下文件ApplicationContext 2.2 web整合struts+hibernate+spring整合版本struts-2.3.33-all spring-framework-3.0.2.RELEASE hibernate-distribution-3.6.10.Final-dist 第一步:jar包整合Struts的jar包 Spring的jar包基础:4+1 , beans、core、context、expression , commons-logging (struts已经导入)AOP:aop联盟(aopalliance)、spring aop 、aspect规范(aspect.weaver)、spring aspectdb:jdbc、tx测试:testweb开发:spring web驱动:mysql连接池:c3p0整合hibernate:spring orm Hibernate的jar包 核心包 required包下的介绍 jpa用于注解开发@Entity @Id 整合log4j导入 log4j…jar (struts已经导入) 整合(过渡):slf4j-log4j12-1.7.2.jar 二级缓存Commons-loggin.jar已经存在 整合包spring整合hibernate: spring orm struts 整合spring:struts2-spring-plugin-2.3.15.3.jar 删除重复jar包 第二步:spring整合hibernate的单元测试创建表create table t_user( id int primary key auto_increment, username varchar(50), password varchar(32), age int ); po类和映射文件 public class User { private Integer id; private String username; private String password; private Integer age; <class name=*”com.gyf.borrowsys.domain.User”* table=*”t_user”> <id name=“id”> <generator class=“native”> <property name=“username”> <property name=“password”> <property name=“age”*> dao Service hibernate.cfg.xml <property name=*”hibernate.connection.driver_class”>com.mysql.jdbc.Driver <property name=“hibernate.connection.url”>jdbc:mysql://localhost:3306/web_ssh <property name=“hibernate.connection.username”>root <property name=“hibernate.connection.password”>123456 <property name=“show_sql”>true <property name=“format_sql”>true <property name=“hibernate.hbm2ddl.auto”>update <property name=“hibernate.dialect”>org.hibernate.dialect.MySQL5Dialect <mapping resource=“com/gyf/borrowsys/domain/User.hbm.xml”*/> applicationContext.xml 单元测试 配置Hibrenate的事务 简化:去除hibernate.cfg.xml文件 org.hibernate.dialect.MySQL5Dialect true true update thread 第三步:spring整合struts编写action类,并将其配置给spring ,spring可以注入service 编写struts.xml 表单jsp页面 web.xml 配置1.确定配置文件contextConfigLocation 2.配置监听器 ContextLoaderListener 3.配置前端控制器 StrutsPrepareAndExecuteFitler contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* action和spring配置文件 action中service默认会根据名称注入**默认情况下框架使用的自动装配策略是name,也就是说框架会去 Spring中寻找与action属性名字相同的bean** actoin对象由spring创建]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring第2天]]></title>
<url>%2F2019%2F08%2F26%2FSpring%E7%AC%AC2%E5%A4%A9%2F</url>
<content type="text"><![CDATA[1、AOP1.1 AOP概述1) 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。 2) AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。 3) 利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 4) AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码 5) 经典应用:事务管理、性能监视、安全检查、缓存 、日志等**【画图】** 6) Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码 7) AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入 1.2 AOP实现原理a. aop底层将采用代理机制进行实现。 b. 接口 + 实现类 :spring采用 jdk 的动态代理Proxy。 c. 实现类:spring 采用 cglib字节码增强。 1.3 AOP术语1.target:目标类,需要被代理的类。例如:UserService 2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法 3.PointCut 切入点:已经被增强的连接点。例如:addUser() 4.advice 通知/增强,增强代码。例如:after、before 5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程. 6.proxy 代理类 7. Aspect(切面): 是切入点pointcut和通知advice的结合 一个线是一个特殊的面。 一个切入点和一个通知,组成成一个特殊的面。 1.4 手动代理1.4.1 JDK动态代理目标类 切面类 工厂类 测试类 1.4.2 cglib 增强字节码n 没有接口,只有实现类。 n 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。 n 导入jar包: 自己导包(了解): 核心:hibernate-distribution-3.6.10.Final\lib\bytecode\cglib\cglib-2.2.jar 依赖:struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib\asm-3.3.jar spring-core..jar 已经整合以上两个内容 工厂类 测试结果 1.5 AOP联盟通知类型AOP联盟为通知Advice定义了org.aopalliance.aop.AdviceSpring按照通知Advice在目标类方法的连接点位置,可以分为5类 •前置通知 org.springframework.aop.MethodBeforeAdvice •在目标方法执行前实施增强 •后置通知 org.springframework.aop.AfterReturningAdvice •在目标方法执行后实施增强 •环绕通知 org.aopalliance.intercept.MethodInterceptor •在目标方法执行前后实施增强 •异常抛出通知 org.springframework.aop.ThrowsAdvice •在方法抛出异常后实施增强 •引介通知 org.springframework.aop.IntroductionInterceptor 在目标类中添加一些新的方法和属性 环绕通知,必须手动执行目标方法try{ //前置通知 //执行目标方法 //后置通知} catch(){ //抛出异常通知} 1.6 Spring编写代理半自动目标:掌握让spring 创建代理对象,从spring容器中手动的获取代理对象。 第一步:导Jar包【核心4+1 、AOP联盟(规范)、spring-aop (实现)】 第二步:目标类 第三步:切面类 第四步:spring配置 第五步:测试 1.7 Spring AOP全自动编程目录:明白什么是全自动织入 第一步:**导入jar包**spring-framework-3.0.2.RELEASE-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE 第二步:Spring 的AOP配置 第三步:测试 2、**AspectJ**2.1 AspectJ简介v AspectJ是一个基于Java语言的AOP框架 v Spring2.0以后新增了对AspectJ切点表达式支持 v @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面 v 新版本Spring框架,建议使用AspectJ方式来开发AOP v 主要用途:自定义开发 2.2 切入点表达式【掌握】execution()用于描述方法 【掌握】 语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常) 修饰符,一般省略 public 公共方法 * 任意 返回值,不能省略 void 返回没有值 String 返回值字符串 * 任意 包,[省略] com.gyf.crm 固定包 com.gyf.crm.*.service crm包下面子包任意 (例如:com.gyf.crm.staff.service) com.gyf.crm.. crm包下面的所有子包(含自己) com.gyf.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包 类,[省略] UserServiceImpl 指定类 *Impl 以Impl结尾 User* 以User开头 * 任意 方法名,不能省略 addUser 固定方法 add* 以add开头 *Do 以Do结尾 * 任意 (参数) () 无参 (int) 一个整型 (int ,int) 两个 (..) 参数任意 throws ,可省略,一般不写。 案例1: execution(com.gyf.crm..service...(..)) 案例2:或 <aop:pointcut expression=”execution(* com.gyf.crm.service.*.*(..)) || execution(* com.gyf.*Do.*(..))” id=”myPointCut”/> within:匹配包或子包中的方法(了解) within(com.gyf.aop..*) this:匹配实现接口的代理对象中的方法(了解) this(com.gyf.aop.user.UserDAO) target:匹配实现接口的目标对象中的方法(了解) target(com.gyf.aop.user.UserDAO) args:匹配参数格式符合标准的方法(了解) args(int,int) bean(id)对指定的bean所有的方法(了解) bean(‘userServiceId’) 2.3 AspectJ 通知类型aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。aspectj 通知类型,只定义类型名称,以及方法格式。个数:6种,知道5种,掌握1中。 before:前置通知(应用:各种校验) 在方法执行前执行,如果通知抛出异常,阻止方法运行 afterReturning:后置通知(应用:常规数据处理) 方法正常返回后执行,如果方法中抛出异常,通知无法执行 必须在方法执行后才执行,所以可以获得方法的返回值。 around:环绕通知(应用:十分强大,可以做任何事情) 方法执行前后分别执行,可以阻止方法的执行 必须手动执行目标方法 afterThrowing:抛出异常通知(应用:包装异常信息) 方法抛出异常后执行,如果方法没有抛出异常,无法执行 after:最终通知(应用:清理现场) 方法执行完毕后执行,无论方法中是否出现异常 查看源码 2.4 Aspect案例讲解【其于xml】第一步:导包 AOP联盟规范 AOP实现 规范 aspectj实现 第二步:实现类和切面类 第三步:spring的xml配置 第四步:测试 2.5 Aspect案例讲解【其于xml】第1步:声明使用注解 第2步:替换service和 切面 bean 第3步:声明切面 第4步:声明前置通知 第5步:声明公共切入点 第6步:声明后置通知 第7步:声明环绕通知 第8步:声明异常通知 第9步:声明最终通知 注解总结@Aspect 声明切面,修饰切面类,从而获得 通知。 通知 @Before 前置 @AfterReturning 后置 @Around 环绕 @AfterThrowing 抛出异常 @After 最终 切入点 @PointCut ,修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用 3 JdbcTemplate3.1 简介Ø jdbcTemplate类似人DBUtils,用于操作Jdbc的工具类,它需要依赖于连接池DataSource(数据源) Ø JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API Ø ODBC(Open Database Connectivity,ODBC)开放数据库连接,是微软公司开提供了一组对数据库访问的标准API(应用程序编程接口) Ø DBCP(DataBase Connection Pool)数据库连接池,是java数据库连接池的一种,由Apache开发 Ø C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。 c3p0与dbcp区别 dbcp没有自动回收空闲连接的功能 c3p0有自动回收空闲连接功能 3.2 环境搭建创建数据库和表create database spring_day02;use spring_day02;create table t_user( id int primary key auto_increment, username varchar(50), password varchar(32)); insert into t_user(username,password) values(‘jack’,’520’);insert into t_user(username,password) values(‘rose’,’521’); 创建工程导入Jar包 创建JavaBean,数据模型 3.3 API使用【了解】 3.4 配置DBCP beans.xml 测试 3.5 配置c3p0 3.6 使用JdbcDaoSupportdao层 Beans.xml 源码分析通过数据源创建模板 3.7 配置properties目数据库的连接信息配置到一个独立的文件中 在src写个db.properties文件 beans.xml]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring第1天]]></title>
<url>%2F2019%2F08%2F26%2FSpring%E7%AC%AC1%E5%A4%A9%2F</url>
<content type="text"><![CDATA[1 Spring介绍1.1 Spring概述Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。 1.2 Spring好处方便解耦,简化开发: Ø Spring就是一个大工厂,专门负责生成Bean,可以将所有对象创建和依赖关系维护由Spring管理 AOP**编程的支持:** Ø Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能 Ø 声明式事务的支持: 只需要通过配置就可以完成对事务的管理,而无需手动编程 方便程序的测试: Ø Spring对Junit4支持,可以通过注解方便的测试Spring程序 方便集成各种优秀框架: Ø Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的支持 降低JavaEE API的使用难度 Spring: Ø 对JavaEE开发中一些难用的API(JDBC、JavaMail、远程调webservice用等),都提供了封装,使这些API应用难度大大降低 1.3 Spring体系结构Spring 框架是一个分层架构,,它包含一系列的功能要素并被分为大约20个模块。这些模块分为Core Container、Data Access/Integration、Web、AOP(Aspect Oriented Programming)、Instrumentation和测试部分,如下图所示: 1.4 在项目中的架构web层:Struts,SpringMVC dao层:Hibernate,mybatis 2 Spring 快速入门目标:掌握web中集成Spring需要哪些包 掌握IOC是什么 2.1 编写流程l 下载Spring 开发包 l 导入Spring的jar包 l 配置Spring的核心xml文件 l 在程序中读取Spring的配置文件来获取Bean【Bean其实就是一个new好的对象】 2.2 下载官网v Spring现在有很多框架,如Spring SpringMVC,Spring-Data,Sprint-Boot 2.3 Spring的核心jar包 spring-core-3.2.2.RELEASE.jar包含Spring框架基本的核心工具类,Spring其它组件要都要使用到这个包里的类,是其它组件的基本核心。 spring-beans-3.2.2.RELEASE.jar所有应用都要用到的,它包含访问配置文件、创建和管理bean以及进行Inversion of Control(IoC) / Dependency Injection(DI)操作相关的所有类 spring-context-3.2.2.RELEASE.jarSpring提供在基础IoC功能上的扩展服务,此外还提供许多企业级服务的支持,如邮件服务、任务调度、JNDI定位、EJB集成、远程访问、缓存以及各种视图层框架的封装等。 spring-expression-3.2.2.RELEASE.jarSpring表达式语言 com.springsource.org.apache.commons.logging-1.1.1.jar第三方的主要用于处理日志 2.4 Spring的入门案例第一步:² 下载Spring的包 spring-framework-3.2.0.RELEASE-dist.zip 【Spring的核心包】spring-framework-3.0.2.RELEASE-dependencies.zip 【Spring的依赖包】 第二步:² 创建Web项目,导Spring的jar包 n 导入4核心(beans、core、context,expression) + 1个依赖(common-logging.jar) n 注意导入时,不要导入带sources的源文件了 第三步:² 写个简单的Service 并在main方法中调用 第四步:² Spring IoC控制反转创建实例 1> 写了个配置文件beans.xml,配置文件的约束可以访问 spring-framework-3.2.0.RC2-docs/reference/html/xsd-config.html网页查看 2> 离线配置文件约束提示的配置 xsd可以在schema目录中找 3> Beans.xml文件配置 第五步:² 从beans.xml获取bean 总结:【IoC】1) IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建**User**Service对象控制权被反转到了Spring框架 2.5 DI解释² Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。 例子:在UserService中提供一个get/set的name方法,在beans.xml中通过property去注入 3、**加载Spring容器的三种方式**3.1 类路径获得配置文件ApplicationContext context = new ClassPathXmlApplicationContext(“com/gyf/spring/demo01/beans.xml”); 3.2 文件系统路径获得配置文件 3.3使用BeanFactory(了解) 3.4BeanFactory和ApplicationContext对比Ø BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean Ø ApplicationContext是对BeanFactory扩展,提供了更多功能 l 国际化处理 l 事件传递 l Bean自动装配 l 各种不同应用层的Context实现 4、**装配Bean(xml)**4.1 实例化Bean的三种方式4.1.1 使用构造方法实例化4.1.2 使用静态工厂方法实例化 Bean.xml ** ** <bean id**=”userService1”* class**=”com.gyf.service.UserServiceImpl”></bean**> *<!– 第二种方式:通过静态工厂方法 spring的版本过低,3.0版本,把jdk改成1.7 –> <bean id**=”userService2”* class**=”com.gyf.service.UserSereviceFactory1”** factory-method**=”createUserService”></bean**> * ** <bean id**=”factory2”** class**=”com.gyf.service.UserSereviceFactory2”></bean> <bean** id**=”userService3”** factory-bean**=”factory2”** factory-method**=”createUserService”></bean**> test @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext(“beans3.xml”); //new 对象 //IUserService userService1 = (IUserService) context.getBean(“userService1”); //userService1.add(); //静态工厂 //IUserService userService2 = UserSereviceFactory1.createUserService(); //IUserService userService2 = (IUserService) context.getBean(“userService2”); //userService2.add(); //实例工厂 //1.创建工厂 // UserSereviceFactory2 factory2 = new UserSereviceFactory2(); //IUserService userService3 = factory2.createUserService(); IUserService userService3 = (IUserService) context.getBean(“userService3”); userService3.add(); } 4.1.3 使用实例工厂方法实例化4.2 bean的作用域掌握红色两个常用的即可 类别 说明 singleton 在Spring IoC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值 prototype 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,相当于执行new XxxBean() request 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境 session 同一个HTTP Session 共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext 环境 globalSession 一般用于Portlet应用环境,该作用域仅适用于WebApplicationContext 环境 案例: 5、bean的生命周期【了解】生命周期图 生命周期图解释1.instantiate bean对象实例化 2.populate properties 封装属性 3.如果Bean实现BeanNameAware 执行 setBeanName 4.如果Bean实现BeanFactoryAware 执行setBeanFactory ,获取Spring容器 5.如果存在类实现 BeanPostProcessor(后处理Bean) ,执行postProcessBeforeInitialization 6.如果Bean实现InitializingBean 执行 afterPropertiesSet 7.调用 指定初始化方法 init 8.如果存在类实现 BeanPostProcessor(处理Bean) ,执行postProcessAfterInitialization 执行业务处理 9.如果Bean实现 DisposableBean 执行 destroy 101.调用 指定销毁方法 customerDestroy 演示 6、**依赖注入Bean属性(xml)**6.1**手动装配,使用xml配置**构造方法注入 属性setter方法注入setter方法有两种注入,一般使用第一种直观 <bean id=*”user”* class=*”com.gyf.spring.demo04.User”> <property name=“username”* value=*”zhangsan”> <property name=“password”* value=*”123456”*> p命名空间注入【了解】 6.2 SpEL表达式【了解】Spring 表达式 Ø 对进行统一编程,所有的内容都使用value Ø #{123}、#{‘jack’} : 数字、字符串 #{beanId} :另一个bean引用 #{beanId.propName} :操作数据 #{beanId.toString()} :执行方法 #{T(类).字段|方法} :静态方法或字段 6.3 集合注入集合的注入都是给添加子标签 数组: List: Set: Map: ,map存放k/v 键值对,使用描述 Properties: 【】 普通数据: 引用数据: List Set Map Properties 数组 6.4 注解注入Ø 注解:就是一个类,使用@注解名称 Ø 开发中:使用注解 取代 xml配置文件。 6.4.1 @Component@component取代 6.4.2 @Component(“id”)取代 6.4.4 web开发,提供3个@Component注解衍生注解(功能一样)取代@Repository(“名称”):dao层 @Service(“名称”):service层 @Controller(“名称”):web层 @Autowired:自动根据类型注入 @Qualifier(“名称”):指定自动注入的id名称 @Resource(“名称”) @ PostConstruct 自定义初始化 @ PreDestroy 自定义销毁 6.4.5 使用案例第一个案例 第二个案例 第三个案例 第四个案例 第五个案例 第六个案例]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>Spring</tag>
</tags>
</entry>
<entry>
<title><![CDATA[三十、Spring Boot生产部署-注意事项和如何使用脚本详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%B8%89%E5%8D%81%E3%80%81Spring-Boot%E7%94%9F%E4%BA%A7%E9%83%A8%E7%BD%B2-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9%E5%92%8C%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E8%84%9A%E6%9C%AC%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十九、Spring Boot集成Swagger详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%B9%9D%E3%80%81Spring-Boot%E9%9B%86%E6%88%90Swagger%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十八、Spring Boot整合Druid详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E5%85%AB%E3%80%81Spring-Boot%E6%95%B4%E5%90%88Druid%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十七、Spring Boot整合MyBatis详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%B8%83%E3%80%81Spring-Boot%E6%95%B4%E5%90%88MyBatis%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十六、Spring Boot生产准备-基于HTTP的监控]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E5%85%AD%E3%80%81Spring-Boot%E7%94%9F%E4%BA%A7%E5%87%86%E5%A4%87-%E5%9F%BA%E4%BA%8EHTTP%E7%9A%84%E7%9B%91%E6%8E%A7%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十五、Spring Boot如何进行远程调试详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%BA%94%E3%80%81Spring-Boot%E5%A6%82%E4%BD%95%E8%BF%9B%E8%A1%8C%E8%BF%9C%E7%A8%8B%E8%B0%83%E8%AF%95%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十四、Spirng Boot使用Spring Session实现集群-redis详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E5%9B%9B%E3%80%81Spirng-Boot%E4%BD%BF%E7%94%A8Spring-Session%E5%AE%9E%E7%8E%B0%E9%9B%86%E7%BE%A4-redis%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十三、Spring Boot发送邮件-使用模板邮件并实现多账号轮询发送]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%B8%89%E3%80%81Spring-Boot%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6-%E4%BD%BF%E7%94%A8%E6%A8%A1%E6%9D%BF%E9%82%AE%E4%BB%B6%E5%B9%B6%E5%AE%9E%E7%8E%B0%E5%A4%9A%E8%B4%A6%E5%8F%B7%E8%BD%AE%E8%AF%A2%E5%8F%91%E9%80%81%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十二、Spring Boot调用REST服务-如何使用代理详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%BA%8C%E3%80%81Spring-Boot%E8%B0%83%E7%94%A8REST%E6%9C%8D%E5%8A%A1-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%90%86%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十一、Spring Boot使用异步消息服务-AMQP(RabbitMQ)详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E4%B8%80%E3%80%81Spring-Boot%E4%BD%BF%E7%94%A8%E5%BC%82%E6%AD%A5%E6%B6%88%E6%81%AF%E6%9C%8D%E5%8A%A1-AMQP-RabbitMQ-%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二十、Spring Boot使用异步消息服务JMS(ActiveMQ)]]></title>
<url>%2F2019%2F08%2F26%2F%E4%BA%8C%E5%8D%81%E3%80%81Spring-Boot%E4%BD%BF%E7%94%A8%E5%BC%82%E6%AD%A5%E6%B6%88%E6%81%AF%E6%9C%8D%E5%8A%A1JMS-ActiveMQ%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十九、Spring Boot之使用Caching-Redis详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%B9%9D%E3%80%81Spring-Boot%E4%B9%8B%E4%BD%BF%E7%94%A8Caching-Redis%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十八、Spring Boot之使用Caching-EhCache详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E5%85%AB%E3%80%81Spring-Boot%E4%B9%8B%E4%BD%BF%E7%94%A8Caching-EhCache%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十七、Spring Boot整合NoSQL数据库-mongodb详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%B8%83%E3%80%81Spring-Boot%E6%95%B4%E5%90%88NoSQL%E6%95%B0%E6%8D%AE%E5%BA%93-mongodb%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十六、Spring Boot整合NoSQL数据库-redis详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E5%85%AD%E3%80%81Spring-Boot%E6%95%B4%E5%90%88NoSQL%E6%95%B0%E6%8D%AE%E5%BA%93-redis%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十五、Spring Boot之h2嵌入式数据库的使用详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%BA%94%E3%80%81Spring-Boot%E4%B9%8Bh2%E5%B5%8C%E5%85%A5%E5%BC%8F%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9A%84%E4%BD%BF%E7%94%A8%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring-Boot之h2嵌入式数据库的使用详解什么是h2嵌入式数据库? H2是一个Java编写的关系型数据库,它可以被嵌入Java应用程序中使用,或者作为一个单独的数据库服务器运行。 H2数据库的前身是 HypersonicSQL,它的名字的含义是 Hypersonic2,但是它的代码是从头开始编写的,没有使用HypersonicSQL或者HSQLDB的代码。 Spring Boot使用 SQL 关系型数据库-h2 嵌入式数据库的步骤 1、添加依赖 123456一、添加依赖<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency> 2、在application.properties配置如下代码 12345#h2#spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSEspring.datasource.url=jdbc:h2:file:D:/roncoo_h2/roncoo_spring_boot;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSEspring.datasource.username=saspring.datasource.password= 注: 1.”~”这个符号代表的就是当前登录到操作系统的用户对应的用户目录 2.账号密码我们指定之后,就会自动创建 指定路径: spring.datasource.url=jdbc:h2:file:D:/roncoo_h2/roncoo_spring_ boot;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE 内存模式: spring.datasource.url=jdbc:h2:mem:test 三、进入控制台 路径:http://localhost:8080/h2-console]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十四、Spring Boot之事务处理详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E5%9B%9B%E3%80%81Spring-Boot%E4%B9%8B%E4%BA%8B%E5%8A%A1%E5%A4%84%E7%90%86%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[使用 SQL 数据库-事务处理一、事务有四个特性:ACID原子性(Atomicity):事务是一个原子操作,由一系列动作组成。事务的原子性确保动作要么全部完成要么完全不起作用。 一致性(Consistency):一旦事务完成(不管成功还是失败),系统必须确保它所建模的业务处于一致的态,而不会是部分完成部分失败。在现实中的数据不应该被破坏。 隔离性(Isolation):可能有许多事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来防止数据损坏。 持久性(Durability):一旦事务完成,无论发生什么系统错误,它的结果都不应该受到影响,这样就能任何系统崩溃中恢复过来。通常情况下,事务的结果被写到持久化存储器中。 二、传播行为 当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。例如:方法可能继续在现有事务中行,也可能开启一个新事务,并在自己的事务中运行。 Spring 定义了七种传播行为:PROPAGATION_REQUIRED 表示当前方法必须运行在事务中。如果当前事务存在,方法将会在该事务中运行。否则,会启动一个新的事务,Spring 默认使用 PROPAGATION_SUPPORTS 表示当前方法不需要事务上下文,但是如果存在当前事务的话,那么该方法会在这个事务中运行 PROPAGATION_MANDATORY 表示该方法必须在事务中运行,如果当前事务不存在,则会抛出一个异常 PROPAGATION_REQUIRED_NEW 表示当前方法必须运行在它自己的事务中。一个新的事务将被启动。如存在当前事务,在该方法执行期间,当前事务会被挂起。如果使用 JTATransactionManager 的话,则需访问 TransactionManager PROPAGATION_NOT_SUPPORTED 表示该方法不应该运行在事务中。如果存在当前事务,在该方法运行期间,当前事务将被挂起。如果使用 JTATransactionManager 的话,则需要访问 TransactionManagerPROPAGATION_NEVER 表示当前方法不应该运行在事务上下文中。如果当前正有一个事务在运行,则会抛出异常 PROPAGATION_NESTED 表示如果当前已经存在一个事务,那么该方法将会在嵌套事务中运行。嵌套的事务可以独立于当前事务进行单独地提交或回滚。如果当前事务不存在,那么其行为与PROPAGATION_REQUIRED 一样。注意各厂商对这种传播行为的支持是有所差异的。可以参考资源管理器的文档来确认它们是否支持嵌套事务 三、隔离级别 隔离级别定义了一个事务可能受其他并发事务影响的程度。 ISOLATION_DEFAULT 使用后端数据库默认的隔离级别,Spring 默认使用,mysql 默认的隔离级别为:Repeatable Read(可重复读) ISOLATION_READ_UNCOMMITTED 读未提交,最低的隔离级别,允许读取尚未提交的数据变更,可能会导脏读、幻读或不可重复读 ISOLATION_READ_COMMITTED 读已提交,允许读取并发事务已经提交的数据,可以阻止脏读,但是幻Spring Boot 基础教程作者:冯永伟或不可重复读仍有可能发生 ISOLATION_REPEATABLE_READ 可重复读,对同一字段的多次读取结果都是一致的,除非数据是被本身务自己所修改,可以阻止脏读和不可重复读,但幻读仍有可能发生 ISOLATION_SERIALIZABLE 可串行化,最高的隔离级别,完全服从 ACID 的隔离级别,确保阻止脏读、不重复读以及幻读,也是最慢的事务隔离级别,因为它通常是通过完全锁定事务相关的数据库表来实现的 脏读(Dirty reads)——脏读发生在一个事务读取了另一个事务改写但尚未提交的数据时。如果改写再稍后被回滚了,那么第一个事务获取的数据就是无效的。 不可重复读(Nonrepeatable read)——不可重复读发生在一个事务执行相同的查询两次或两次以上是每次都得到不同的数据时。这通常是因为另一个并发事务在两次查询期间进行了更新。 幻读(Phantom read)——幻读与不可重复读类似。它发生在一个事务(T1)读取了几行数据,接着另个并发事务(T2)插入了一些数据时。在随后的查询中,第一个事务(T1)就会发现多了一些原本不存的记录。 四、属性说明 @Transactional a、isolation:用于指定事务的隔离级别。默认为底层事务的隔离级别。 b、noRollbackFor:指定遇到指定异常时强制不回滚事务。 c、noRollbackForClassName:指定遇到指定多个异常时强制不回滚事务。该属性可以指定多个异常类名。 d、propagation:指定事务的传播属性。 e、readOnly:指定事务是否只读。表示这个事务只读取数据但不更新数据,这样可以帮助数据库引擎优化事务。若真的是一个只读取的数据库应设置 readOnly=true f、rollbackFor:指定遇到指定异常时强制回滚事务。 g、rollbackForClassName:指定遇到指定多个异常时强制回滚事务。该属性可以指定多个异常类名。 h、timeout:指定事务的超时时长。 使用Spring Boot处理事务的步骤1、创建RoncooUser实体类 123456789101112131415package com.roncoo.education.bean;import java.util.Date;/** * 实体类 * * @author wujing */public class RoncooUser { private int id; private String name; private Date createTime; //省略getter、setter和toString方法} 2.创建RoncooUserDao接口类 123456789101112131415161718192021222324252627282930313233343536373839404142package com.roncoo.education.dao;import com.roncoo.education.bean.RoncooUser;/** * @author wujing */public interface RoncooUserDao { /** * 插入 * * @param roncooUser * @return */ int insert(RoncooUser roncooUser); /** * 删除 * * @param id * @return */ int deleteById(int id); /** * 更新 * * @param roncooUser * @return */ int updateById(RoncooUser roncooUser); /** * 查找 * * @param id * @return */ RoncooUser selectById(int id);} 3.创建UserService类 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152package com.roncoo.education.service;import java.util.Date;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.roncoo.education.bean.RoncooUser;import com.roncoo.education.bean.RoncooUserLog;import com.roncoo.education.dao.RoncooUserDao;import com.roncoo.education.dao.RoncooUserLogDao;@Servicepublic class UserService { @Autowired private RoncooUserDao roncooUserDao; @Autowired private RoncooUserLogDao roncooUserLogDao; /** * 用户注册 * * @return */ @Transactional public String register(String name, String ip) { // 1.添加用户 RoncooUser roncooUser = new RoncooUser(); roncooUser.setName(name); roncooUser.setCreateTime(new Date()); roncooUserDao.insert(roncooUser); // 测试使用 boolean flag = true; if (flag) { throw new RuntimeException(); } // 2.添加注册日志 RoncooUserLog roncooUserLog = new RoncooUserLog(); roncooUserLog.setUserName(name); roncooUserLog.setUserIp(ip); roncooUserLog.setCreateTime(new Date()); roncooUserLogDao.save(roncooUserLog); return "success"; }} 4.测试 123456789101112131415161718192021222324package com.roncoo.education;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import com.roncoo.education.service.UserService;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringBootDemo151ApplicationTests { @Autowired private UserService userService; @Test public void register() { String result = userService.register("无境ff", "192.168.1.1"); System.out.println(result); }}]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十三、Spring Boot整合Spring-data-jpa详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%B8%89%E3%80%81Spring-Boot%E6%95%B4%E5%90%88Spring-data-jpa%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot Jpa 介绍首先了解 Jpa 是什么?Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范。它为 Java 开发人员提供了一种对象/关联映射工具来管理 Java 应用中的关系数据。它的出现主要是为了简化现有的持久化开发工作和整合 ORM 技术,结束现在 Hibernate,TopLink,JDO 等 ORM 框架各自为营的局面。 值得注意的是,Jpa是在充分吸收了现有 Hibernate,TopLink,JDO 等 ORM 框架的基础上发展而来的,具有易于使用,伸缩性强等优点。从目前的开发社区的反应上看,Jpa 受到了极大的支持和赞扬,其中就包括了 Spring 与 EJB3. 0的开发团队。 注意:Jpa 是一套规范,不是一套产品,那么像 Hibernate,TopLink,JDO 他们是一套产品,如果说这些产品实现了这个 Jpa 规范,那么我们就可以叫他们为 Jpa 的实现产品。 Spring Boot JpaSpring Boot Jpa 是 Spring 基于 ORM 框架、Jpa 规范的基础上封装的一套 Jpa 应用框架,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data Jpa 可以极大提高开发效率! Spring Boot Jpa 让我们解脱了 DAO 层的操作,基本上所有 CRUD 都可以依赖于它来实现 基本查询基本查询也分为两种,一种是 Spring Data 默认已经实现,一种是根据查询的方法来自动解析成 SQL。 预先生成方法Spring Boot Jpa 默认预先生成了一些基本的CURD的方法,例如:增、删、改等等 1 继承 JpaRepository 12public interface UserRepository extends JpaRepository<User, Long> {}//集成JpaRepository,泛型里面第一个是User类,第二个Long是int类型的值 2 使用默认方法 123456789@Testpublic void testBaseQuery() throws Exception { User user=new User(); userRepository.findAll(); userRepository.findOne(1l); userRepository.save(user); userRepository.delete(user); userRepository.count(); userRepository.exists(1l); // ...} 就不解释了根据方法名就看出意思来 自定义简单查询自定义的简单查询就是根据方法名来自动生成 SQL,主要的语法是 findXXBy, readAXXBy, queryXXBy, countXXBy, getXXBy后面跟属性名称: 1User findByUserName(String userName); 也使用一些加一些关键字 And、 Or 1User findByUserNameOrEmail(String username, String email); 修改、删除、统计也是类似语法 1Long deleteById(Long id);Long countByUserName(String userName); 基本上 SQL 体系中的关键词都可以使用,例如: LIKE、 IgnoreCase、 OrderBy。 1List<User> findByEmailLike(String email);User findByUserNameIgnoreCase(String userName);List<User> findByUserNameOrderByEmailDesc(String email); 具体的关键字,使用方法和生产成SQL如下表所示 Keyword Sample JPQL snippet And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2 Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2 Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1 Between findByStartDateBetween … where x.startDate between ?1 and ?2 LessThan findByAgeLessThan … where x.age < ?1 LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1 GreaterThan findByAgeGreaterThan … where x.age > ?1 GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1 After findByStartDateAfter … where x.startDate > ?1 Before findByStartDateBefore … where x.startDate < ?1 IsNull findByAgeIsNull … where x.age is null IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null Like findByFirstnameLike … where x.firstname like ?1 NotLike findByFirstnameNotLike … where x.firstname not like ?1 StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %) EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %) Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %) OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc Not findByLastnameNot … where x.lastname <> ?1 In findByAgeIn(Collection ages) … where x.age in ?1 NotIn findByAgeNotIn(Collection age) … where x.age not in ?1 TRUE findByActiveTrue() … where x.active = true FALSE findByActiveFalse() … where x.active = false IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1) 复杂查询在实际的开发中我们需要用到分页、删选、连表等查询的时候就需要特殊的方法或者自定义 SQL 分页查询分页查询在实际使用中非常普遍了,Spring Boot Jpa 已经帮我们实现了分页的功能,在查询的方法中,需要传入参数 Pageable ,当查询中有多个参数的时候 Pageable建议做为最后一个参数传入. 1Page<User> findALL(Pageable pageable);Page<User> findByUserName(String userName,Pageable pageable); Pageable 是 Spring 封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则 123456@Testpublic void testPageQuery() throws Exception { int page=1,size=10; Sort sort = new Sort(Direction.DESC, "id"); Pageable pageable = new PageRequest(page, size, sort); userRepository.findALL(pageable); userRepository.findByUserName("testName", pageable);} 限制查询 有时候我们只需要查询前N个元素,或者支取前一个实体。 12345User findFirstByOrderByLastnameAsc();User findTopByOrderByAgeDesc();Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);List<User> findFirst10ByLastname(String lastname, Sort sort);List<User> findTop10ByLastname(String lastname, Pageable pageable); 自定义SQL查询其实 Spring Data 觉大部分的 SQL 都可以根据方法名定义的方式来实现,但是由于某些原因我们想使用自定义的 SQL 来查询,Spring Data 也是完美支持的;在 SQL 的查询方法上面使用 @Query注解,如涉及到删除和修改在需要加上 @Modifying.也可以根据需要添加 @Transactional对事物的支持,查询超时的设置等。 123456789@Modifying@Query("update User u set u.userName = ?1 where u.id = ?2")int modifyByIdAndUserId(String userName, Long id);@Transactional@Modifying@Query("delete from User where id = ?1")void deleteByUserId(Long id);@Transactional(timeout = 10)@Query("select u from User u where u.emailAddress = ?1")User findByEmailAddress(String emailAddress); 多表查询多表查询 Spring Boot Jpa 中有两种实现方式,第一种是利用 Hibernate 的级联查询来实现,第二种是创建一个结果集的接口来接收连表查询后的结果,这里主要第二种方式。 首先需要定义一个结果集的接口类。 12345678public interface HotelSummary { City getCity(); String getName(); Double getAverageRating(); default Integer getAverageRatingRounded() { return getAverageRating() == null ? null : (int) Math.round(getAverageRating()); }} 查询的方法返回类型设置为新创建的接口 12@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating " - "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")Page<HotelSummary> findByCity(City city, Pageable pageable);@Query("select h.name as name, avg(r.rating) as averageRating " - "from Hotel h left outer join h.reviews r group by h")Page<HotelSummary> findByCity(Pageable pageable); 使用 1234Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));for(HotelSummary summay:hotels){ System.out.println("Name" +summay.getName()); } 在运行中 Spring 会给接口(HotelSummary)自动生产一个代理类来接收返回的结果,代码汇总使用 getXX的形式来获取 多数据源的支持同源数据库的多源支持日常项目中因为使用的分布式开发模式,不同的服务有不同的数据源,常常需要在一个项目中使用多个数据源,因此需要配置 Spring Boot Jpa 对多数据源的使用,一般分一下为三步: 1 配置多数据源 2 不同源的实体类放入不同包路径 3 声明不同的包路径下使用不同的数据源、事务支持 异构数据库多源支持比如我们的项目中,即需要对 mysql 的支持,也需要对 Mongodb 的查询等。 实体类声明 @Entity 关系型数据库支持类型、声明 @Document 为 Mongodb 支持类型,不同的数据源使用不同的实体就可以了1234interface PersonRepository extends Repository<Person, Long> { …}@Entitypublic class Person { …}interface UserRepository extends Repository<User, Long> { …}@Documentpublic class User { …} 但是,如果 User 用户既使用 Mysql 也使用 Mongodb 呢,也可以做混合使用 123interface JpaPersonRepository extends Repository<Person, Long> { …}interface MongoDBPersonRepository extends Repository<Person, Long> { …}@Entity@Documentpublic class Person { …} 也可以通过对不同的包路径进行声明,比如 A 包路径下使用 mysql,B包路径下使用 MongoDB 1@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")interface Configuration { } 其它使用枚举 使用枚举的时候,我们希望数据库中存储的是枚举对应的 String 类型,而不是枚举的索引值,需要在属性上面添加 @Enumerated(EnumType.STRING) 注解 1@Enumerated(EnumType.STRING) @Column(nullable = true)private UserType type; 不需要和数据库映射的属性 正常情况下我们在实体类上加入注解 @Entity,就会让实体类和表相关连如果其中某个属性我们不需要和数据库来关联只是在展示的时候做计算,只需要加上 @Transient属性既可。 1@Transientprivate String userName; 使用Spring Boot Jpa的步骤1、配置数据源:在application.properties或者application.yaml配置文件中配置数据库连接配置,如下代码 123456789#数据库连接配置spring.datasource.url=jdbc:mysql://localhost:3307/spring_boot_demo?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver# JPAspring.jpa.hibernate.ddl-auto= updatespring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto= update:修改代码后,sql语句自动更新 2.配置pom文件:在pom文件中添加如下依赖: 12345678910<!-- 数据库 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency> 3.创建数据库:创建一个spring_boot_demo的数据库 4.在bean包里面创建一个RoncooUserLog的实体类12345678910111213141516171819202122232425262728package com.roncoo.education.bean;import java.util.Date;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class RoncooUserLog { @Id @GeneratedValue private Integer id; @Column private Date createTime; @Column private String userName; @Column private String userIp; //省略getter、setter、toString方法} @Entity:实体类声明 @Entity 关系型数据库支持类型 @Id :标识这个属性是主键 @GeneratedValue(strategy = GenerationType.IDENTITY)自增长策略 @Column(nullable = false, length = 20) // 映射为字段,值不能为空 //设置那些字段不能为空 5.创建RoncooUserLogDao的接口RoncooUserLogDao继承JPA中的CrudRepository接口,接口的泛型是<RoncooUserLog,Integer>,既然它继承的接口里面已经提供了方法,那个之前在接口中提供的方法就可以删除掉了 1234567891011121314151617181920212223242526272829303132333435package com.roncoo.education.dao;import java.util.List;import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import com.roncoo.education.bean.RoncooUserLog;public interface RoncooUserLogDao extends JpaRepository<RoncooUserLog, Integer> { /** * @param * @return * 如果JPA中没有满足的需求,我们就会用到@Query()注解,括号里面可以写sql语句 */ @Query(value = "select u from RoncooUserLog u where u.userName=?1") List<RoncooUserLog> findByUserName(String userName); /** * @param string * @param string2 * @return */ List<RoncooUserLog> findByUserNameAndUserIp(String string, String string2); /** * @param * @param pageable * @return */ Page<RoncooUserLog> findByUserName(String userName, Pageable pageable);} 6.创建测试类1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package com.roncoo.education;import java.util.Date;import java.util.List;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;import org.springframework.data.domain.Sort.Direction;import org.springframework.data.domain.Sort.Order;import org.springframework.test.context.junit4.SpringRunner;import com.roncoo.education.bean.RoncooUserLog;import com.roncoo.education.dao.RoncooUserLogDao;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringBootDemo141ApplicationTests { @Autowired private RoncooUserLogDao roncooUserLogDao; @Test public void insert() { RoncooUserLog entity = new RoncooUserLog(); entity.setUserName("无境"); entity.setUserIp("192.168.0.1"); entity.setCreateTime(new Date()); roncooUserLogDao.save(entity); } @Test public void delete() { roncooUserLogDao.delete(1); } @Test public void update() { RoncooUserLog entity = new RoncooUserLog(); entity.setId(2); entity.setUserName("无境2"); entity.setUserIp("192.168.0.1"); entity.setCreateTime(new Date()); roncooUserLogDao.save(entity); } @Test public void select() { RoncooUserLog result = roncooUserLogDao.findOne(1); System.out.println(result); } @Test public void select2() { List<RoncooUserLog> result = roncooUserLogDao.findByUserName("无境"); System.out.println(result); } @Test public void select3() { List<RoncooUserLog> result = roncooUserLogDao.findByUserNameAndUserIp("无境", "192.168.0.1"); System.out.println(result); } // 分页 @Test public void queryForPage() { //Pageable:分页类,分页类的参数类型 0 代表当前第几页,20代表当前页有第几条 , new Sort是排序,排序是按组件倒序来排 Pageable pageable = new PageRequest(0, 20, new Sort(new Order(Direction.DESC, "id"))); Page<RoncooUserLog> result = roncooUserLogDao.findByUserName("无境", pageable); System.out.println(result.getContent()); }}]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十二、Spring Boot整合JdbcTemplate详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%BA%8C%E3%80%81Spring-Boot%E6%95%B4%E5%90%88JdbcTemplate%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[使用 SQL 关系型数据库-JdbcTemplate 一、配置数据源: 嵌入式数据库的支持:Spring Boot 可以自动配置 H2, HSQL and Derby 数据库,不需要提供任何的 链接 URLs,只需要加入相应的 jar 包,Spring boot 可以自动发现装配]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十一、Spring Boot之文件上传详解]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E4%B8%80%E3%80%81Spring-Boot%E4%B9%8B%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[十、Spring Boot CROS支持]]></title>
<url>%2F2019%2F08%2F26%2F%E5%8D%81%E3%80%81Spring-Boot-CROS%E6%94%AF%E6%8C%81%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[九、Spring Boot整合Servlet、Fitter和Listener详解]]></title>
<url>%2F2019%2F08%2F26%2F%E4%B9%9D%E3%80%81Spring-Boot%E6%95%B4%E5%90%88Servlet%E3%80%81Fitter%E5%92%8CListener%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[八、Spring Boot异常处理详解]]></title>
<url>%2F2019%2F08%2F25%2F%E5%85%AB%E3%80%81Spring-Boot%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot异常处理详解]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[六、Spring Boot整合Thymeleaf详解]]></title>
<url>%2F2019%2F08%2F25%2F%E5%85%AD%E3%80%81Spring-Boot%E6%95%B4%E5%90%88Thymeleaf%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Thymeleaf的基本语法和常用方法简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点: 1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。 2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。 3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。 标准表达式语法它们分为四类: 1.变量表达式 2.选择或星号表达式 3.文字国际化表达式 4.URL表达式 变量表达式变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。如下所示:${session.user.name} 它们将以HTML标签的一个属性来表示: 12<span th:text="${book.author.name}"> <li th:each="book : ${books}"> 选择(星号)表达式选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下:*{customer.name} 被指定的object由th:object属性定义: 12345<div th:object="${book}"> ... <span th:text="*{title}">...</span> ... </div> 文字国际化表达式文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选). 12#{main.title} #{message.entrycreated(${entryId})} 可以在模板文件中找到这样的表达式代码: 123456<table> ... <th th:text="#{header.address.city}">...</th> <th th:text="#{header.address.country}">...</th> ... </table> URL表达式URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写。@{/order/list}URL还可以设置参数:@{/order/details(id=${orderId})}相对路径:@{../documents/report} 让我们看这些表达式: 12<form th:action="@{/createOrder}"> <a href="main.html" th:href="@{/main}"> 变量表达式和星号表达有什么区别吗?如果不考虑上下文的情况下,两者没有区别;星号语法评估在选定对象上表达,而不是整个上下文什么是选定对象?就是父标签的值,如下: 12345<div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p></div> 这是完全等价于: 12345<div th:object="${session.user}"> <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p></div> 当然,美元符号和星号语法可以混合使用: 12345<div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p></div> 表达式支持的语法字面(Literals) 文本文字(Text literals): 'one text', 'Another one!',… 数字文本(Number literals): 0, 34, 3.0, 12.3,… 布尔文本(Boolean literals): true, false 空(Null literal): null 文字标记(Literal tokens): one, sometext, main,… 文本操作(Text operations) 字符串连接(String concatenation): + 文本替换(Literal substitutions): |The name is ${name}| 算术运算(Arithmetic operations) 二元运算符(Binary operators): +, -, *, /, % 减号(单目运算符)Minus sign (unary operator): - 布尔操作(Boolean operations) 二元运算符(Binary operators):and, or 布尔否定(一元运算符)Boolean negation (unary operator):!, not 比较和等价(Comparisons and equality) 比较(Comparators): >, <, >=, <= (gt, lt, ge, le) 等值运算符(Equality operators):==, != (eq, ne) 条件运算符(Conditional operators) If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue) 所有这些特征可以被组合并嵌套: 1'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown')) 常用th标签都有那些? 关键字 功能介绍 案例 th:id 替换id <input th:id="'xxx' + ${collect.id}"/> th:text 文本替换 <p th:text="${collect.description}">description</p> th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">conten</p> th:object 替换对象 <div th:object="${session.user}"> th:value 属性赋值 <input th:value="${user.name}" /> th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div> th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" th:onclick 点击事件 th:onclick="'getCollect()'" th:each 属性赋值 tr th:each="user,userStat:${users}"> th:if 判断条件 <a th:if="${userId == collect.userId}" > th:unless 和th:if判断相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> th:switch 多路选择 配合th:case 使用 <div th:switch="${user.role}"> th:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p> th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert"> th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> /> th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div> th:selected selected选择框 选中 th:selected="(${xxx.id} == ${configObj.dd})" th:src 图片类地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript"> th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}"> th:remove 删除某个属性 <tr th:remove="all"> 1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。 th:attr 设置标签属性,多个属性可以用逗号分隔 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。 还有非常多的标签,这里只列出最常用的几个,由于一个标签内可以包含多个th:x属性,其生效的优先级顺序为:include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove。 几种常用的使用方法1、赋值、字符串拼接12<p th:text="${collect.description}">description</p><span th:text="'Welcome to our application, ' + ${user.name} + '!'"> 字符串拼接还有另外一种简洁的写法 1<span th:text="|Welcome to our application, ${user.name}!|"> 2、条件判断 If/UnlessThymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,<a>标签只有在th:if中条件成立时才显示: 12<a th:if="${myself=='yes'}" > </i> </a><a th:unless=${session.user != null} th:href="@{/login}" >Login</a> th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。 也可以使用 (if) ? (then) : (else) 这种语法来判断显示的内容 3、for 循环12345678910 <tr th:each="collect,iterStat : ${collects}"> <th scope="row" th:text="${collect.id}">1</th> <td > <img th:src="${collect.webLogo}"/> </td> <td th:text="${collect.url}">Mark</td> <td th:text="${collect.title}">Otto</td> <td th:text="${collect.description}">@mdo</td> <td th:text="${terStat.index}">index</td></tr> iterStat称作状态变量,属性有: index:当前迭代对象的index(从0开始计算) count: 当前迭代对象的index(从1开始计算) size:被迭代对象的大小 current:当前迭代变量 even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算) first:布尔值,当前循环是否是第一个 last:布尔值,当前循环是否是最后一个 4、URLURL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{…}来处理的。如果需要Thymeleaf对URL进行渲染,那么务必使用th:href,th:src等属性,下面是一个例子 12345<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) --> <a th:href="@{/standard/{type}(type=${type})}">view</a><!-- Will produce '/gtvg/order/3/details' (plus rewriting) --><a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a> 设置背景 1<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div> 根据属性值改变背景 1<div class="media-object resource-card-image" th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div> 几点说明: 上例中URL最后的(orderId=${o.id}) 表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性 @{...}表达式中可以通过{orderId}访问Context中的orderId变量 @{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order 5、内联js内联文本:[[…]]内联文本的表示方式,使用时,必须先用th:inline=”text/javascript/none”激活,th:inline可以在父级标签内使用,甚至作为body的标签。内联文本尽管比th:text的代码少,不利于原型显示。 12345678<script th:inline="javascript">/*<![CDATA[*/...var username = /*[[${sesion.user.name}]]*/ 'Sebastian';var size = /*[[${size}]]*/ 0;.../*]]>*/</script> js附加代码: 123/*[+var msg = 'This is a working application';+]*/ js移除代码: 123/*[- */var msg = 'This is a non-working template';/* -]*/ 6、内嵌变量为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问: dates : java.util.Date的功能方法类。 calendars : 类似#dates,面向java.util.Calendar numbers : 格式化数字的功能方法类 strings : 字符串对象的功能类,contains,startWiths,prepending/appending等等。 objects: 对objects的功能类操作。 bools: 对布尔值求值的功能方法。 arrays:对数组的功能类方法。 lists: 对lists功能类方法 sets maps… 下面用一段代码来举例一些常用的方法: dates123456789101112131415161718/* * Format date with the specified pattern * Also works with arrays, lists or sets */${#dates.format(date, 'dd/MMM/yyyy HH:mm')}${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}/* * Create a date (java.util.Date) object for the current date and time */${#dates.createNow()}/* * Create a date (java.util.Date) object for the current date (time set to 00:00) */${#dates.createToday()} strings12345678910111213141516171819202122232425262728293031323334/* * Check whether a String is empty (or null). Performs a trim() operation before check * Also works with arrays, lists or sets */${#strings.isEmpty(name)}${#strings.arrayIsEmpty(nameArr)}${#strings.listIsEmpty(nameList)}${#strings.setIsEmpty(nameSet)}/* * Check whether a String starts or ends with a fragment * Also works with arrays, lists or sets */${#strings.startsWith(name,'Don')} // also array*, list* and set*${#strings.endsWith(name,endingFragment)} // also array*, list* and set*/* * Compute length * Also works with arrays, lists or sets */${#strings.length(str)}/* * Null-safe comparison and concatenation */${#strings.equals(str)}${#strings.equalsIgnoreCase(str)}${#strings.concat(str)}${#strings.concatReplaceNulls(str)}/* * Random */${#strings.randomAlphanumeric(count)} 使用thymeleaf布局使用thymeleaf布局非常的方便 定义代码片段 123<footer th:fragment="copy"> &copy; 2016</footer> 在页面任何地方引入: 1234<body> <div th:include="footer :: copy"></div> <div th:replace="footer :: copy"></div> </body> th:include 和 th:replace区别,include只是加载,replace是替换 返回的HTML如下: 1234<body> <div> &copy; 2016 </div> <footer>&copy; 2016 </footer></body> 下面是一个常用的后台页面布局,将整个页面分为头部,尾部、菜单栏、隐藏栏,点击菜单只改变content区域的页面 123456789<body class="layout-fixed"> <div th:fragment="navbar" class="wrapper" role="navigation"> <div th:replace="fragments/header :: header">Header</div> <div th:replace="fragments/left :: left">left</div> <div th:replace="fragments/sidebar :: sidebar">sidebar</div> <div layout:fragment="content" id="content" ></div> <div th:replace="fragments/footer :: footer">footer</div> </div></body> 任何页面想使用这样的布局值只需要替换中见的 content模块即可 1234<html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout"> <body> <section layout:fragment="content"> ... 也可以在引用模版的时候传参 1<head th:include="layout :: htmlhead" th:with="title='Hello'"></head> layout 是文件地址,如果有文件夹可以这样写 fileName/layout:htmlheadhtmlhead 是指定义的代码片段 如 th:fragment="copy" Spring Boot整合Thymeleaf的步骤:Spring boot 在spring默认基础上,自动配置添加了以下特性: 包含了ContentNegotiatingViewResolver和BeanNameViewResolver beans。 对静态资源的支持,包括对WebJars的支持。 自动注册Converter,GenericConverter,Formatter beans。 对HttpMessageConverters的支持。 自动注册MessageCodeResolver。 对静态index.html的支持。 对自定义Favicon的支持。 主动使用ConfigurableWebBindingInitializer bean 1、在pom文件中配置如下依赖 1234<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency> 2.在templates文件夹中创建一个index.html 12345678910111213141516171819202122232425<!DOCTYPE html><html xmlns:th="http://www.w3.org/1999/xhtml"><head lang="en"> <title>Spring Boot Demo - FreeMarker</title> <link href="/css/index.css" rel="stylesheet" /></head><body><center> <img src="/images/logo.png" /> <h1 id="title" th:text="${title}"></h1></center><script type="text/javascript" src="/webjars/jquery/2.1.4/jquery.min.js"></script><script> $(function(){ $('#title').click(function(){ alert('点击了'); }); })</script></body></html> 3.在controller包中创建一个WebController 123456789101112131415161718192021package com.lqg.controller;import lombok.extern.slf4j.Slf4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/web")@Slf4jpublic class WebController { private static final Logger logger = LoggerFactory.getLogger(WebController.class); @RequestMapping("/index") public String index(ModelMap map){ map.put("title","hello world"); logger.info("这里是controller"); return "index";//注意,不要在最前面加上/,Linux下会出错 }}]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[七、Spring Boot整合JSP详解]]></title>
<url>%2F2019%2F08%2F25%2F%E4%B8%83%E3%80%81Spring-Boot%E6%95%B4%E5%90%88JSP%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot整合JSP详解]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[五、Spring Boot整合FreeMarker详解]]></title>
<url>%2F2019%2F08%2F25%2F%E4%BA%94%E3%80%81Spring-Boot%E6%95%B4%E5%90%88FreeMarker%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot整合FreeMarker详解]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[四、Spring Boot整合日志详解]]></title>
<url>%2F2019%2F08%2F25%2F%E5%9B%9B%E3%80%81Spring-Boot%E6%95%B4%E5%90%88%E6%97%A5%E5%BF%97%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot整合日志详解]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[MyBatis[从入门到基本精通]]]></title>
<url>%2F2019%2F08%2F25%2FMyBatis-%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E5%9F%BA%E6%9C%AC%E7%B2%BE%E9%80%9A%2F</url>
<content type="text"><![CDATA[MyBatis【从入门到基本精通】 一、MyBatis的基本使用1、MyBatis作用 MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。 MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 MyBatis可以使用简单的XML用于配置和原始映射,将接口和Java的POJO类映射成数据库中的记录 使开发者只需要关注 SQL本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。 2.MyBatis的历史 原是apache的一个开源项目iBatis,2010年6月这个项目由apache software foundation迁移到了google code,并且改名为MyBatis 。iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。 3.为什么要使用MyBatis?JDBC的缺点 SQL夹在Java代码块里,耦合度高导致硬编码内伤 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见 要自已创建connection、创建statement、手动设置参数、结果集检索等 Hibernate的缺点 长难复杂SQL,对于Hibernate而言处理也不容易 内部自动生产的SQL,不容易做特殊优化。 MyBatis的好处: 对开发人员而言,核心sql还是需要自己优化 MyBatis是一个半自动化的持久化层框架。 MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。 二、MyBatis的开发步骤1、下载Mybatis核心包http://www.mybatis.org/mybatis-3/getting-started.html https://github.com/mybatis/mybatis-3/releases 2、创建工程,引入MyBatis核心包及依赖包 3、创建customer表123456781 CREATE TABLE customer(2 cust_id int PRIMARY KEY,3 cust_name varchar(50),4 cust_profession VARCHAR(50),5 cust_phone VARCHAR(50),6 cust_email VARCHAR(50)7 )1234567 4、建立与表对象的domain,创建Customer实体类我在IDEA中用了lombok jar包1234567891011121314151617181920212223242526 package com.lqg.domain; 2 3 import lombok.Getter; 4 import lombok.Setter; 5 6 @Setter@Getter 7 public class Customer { 8 9 private Integer cust_id;10 private String cust_name;11 private String cust_profession;12 private String cust_phone;13 private String cust_email;14 15 @Override16 public String toString() {17 return "Customer{" +18 "cust_id=" + cust_id +19 ", cust_name='" + cust_name + '\'' +20 ", cust_profession='" + cust_profession + '\'' +21 ", cust_phone='" + cust_phone + '\'' +22 ", cust_email='" + cust_email + '\'' +23 '}';24 }25 }12345678910111213141516171819202122232425 5、创建与表对象的关系映射Mapping文件编写sql语句12345678910111213<?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="Mytest"> 6 <!--根据id查询用户--> 7 <select id="queryCustomerById" parameterType="Int" resultType="com.lqg.domain.Customer"> 8 select * from `customer` where cust_id = #{cust_id} 9 </select>10 11 </mapper>123456789101112 6、在核心配置文件当中引入Mapping12345<!--加载映射文件--><mappers><mapper resource="com/lqg/domain/Customer.xml"></mapper></mappers>1234 7、创建工厂,执行sql语句1234567891011121314151617181920212223242526272829303132package com.lqg.test;import com.lqg.domain.Customer;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class MyBatisTest { @Test public void test() throws IOException { //1.创建一个SqlSessionFactoryBulider的类 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //2.加载SqlMapConfig.xml的配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //3.创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); //4.创建SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //5.用sqlSession对象执行查询 Customer customer = sqlSession.selectOne("queryCustomerById",1); System.out.println(customer); }}12345678910111213141516171819202122232425262728293031 8通过用户id查询结果如下: 三. MyBatis的入门程序:4.1、MyBatis的CRUD操作MyBatis查询一个,多个以及增删改 4.4.1通过用户id进行查询对应映射配置 1234<select id="queryCustomerById" parameterType="Int" resultType="com.domain.Customer"> SELECT * FROM `customer` WHERE cust_id = #{cust_id}</select>123 在测试类里面查询 12Customer c = session.selectOne("queryCustomerById", 1);1 查询所有用户在对应的映射文件里面配置 1234<select id="queryAllCustomer" resultType="com.domain.Customer"> select * from customer </select>123 模糊查询(同查询所有差不多) 1234<select id="queryAllByName" parameterType="String" resultType="com.lqg.domain.Customer"> select * from customer where cust_name like '%${value}%'</select>123 4.4.2、总结 parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中 resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。如果有多条数据,则分别进行映射,并把对象放到容器List中 selectOne查询一条记录,如果使用selectOne查询多条记录则抛出异常 selectList可以查询一条或多条记录 #{}表示一个?占位符号,通过#{}可以实现preparedStatement向占位符中设置值自动进行java类型和jdbc类型转换,可以有效防止sql注入#{}可以接收简单类型值或pojo属性值如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称里面的参数传递过来都是加上’’引号的, 表示拼接sql串,可以接收简单类型值或pojo属性值通过{} 表示拼接sql串,可以接收简单类型值或pojo属性值 通过表示拼接s*ql串,可以接收简单类型值或pojo*属性值通过{}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换如果parameterType传输单个简单类型值,${}括号中只能是value 5、保存更新删除5.1添加用户对应关系映射配置 12345<insert id="insertCustomer" parameterType="com.domain.Customer"> insert into `customer` values(#{cust_id},#{cust_name},#{cust_profession}, #{cust_phone},#{cust_email})</insert>1234 注意:如果添加操作后面直接跟的表名,赋值里面的所有字段都要写上包括自动增长的id,如果是跟字段那值就跟上自己写的字段一一对应 5.5.1、添加用户的方法测试代码 12345SqlSession session = MyBatisUtils.openSession(); Customer customer = new Customer("老王","服务员","17364343463","748639224@qq.com"); session.insert("insertCustomer",customer); session.commit();1234 注意:当要修改数据库中的记录的时候,执行sql时候需要自己提交事务 5.5.2、返回添加过后自增的主键两种方式方式一:获取插入最后一个id(写在insert标签里面) 1234<selectKey keyColumn="cust_id" keyProperty="cust_id" resultType="Integer" order="AFTER"> select last_insert_id()</selectKey>123 方式二:获取插入的最后一个id(这种方式比第一种简单)* 1234567<insert id="insertCustomer" parameterType="Customer" useGeneratedKeys="true" keyProperty="cust_id" keyColumn="cust_id"> //keyColumn可以不写 insert into customer(cust_name,cust_profession,cust_phone) values(#{cust_name},#{cust_profession},#{cust_phone});</insert> 123456 5.2更新用户对应关系映射配置 1234<update id="updateCustomerById" parameterType="com.lqg.domain.Customer"> update customer set cust_name =#{cust_name} where cust_id = #{cust_id}</update>123 5.2.1、修改用户的方法测试代码 123456789Customer customer1 = new Customer(); customer1.setCust_id(7); customer1.setCust_name("王麻子"); customer1.setCust_profession("清洁工"); customer1.setCust_email("78754579846"); int row= sqlSession.insert("saveCustomer",customer1); int row2 = sqlSession.update("updateCustomerById",customer1); session.commit();12345678 5.3删除用户对应关系映射配置 1234<delete id="deleteCustomerById" parameterType="com.lqg.domain.Customer"> delete from customer where cust_id=#{cust_id}</delete>123 5.3.1、修改用户的方法测试代码 12345678910 Customer customer1 = new Customer(); customer1.setCust_id(7); customer1.setCust_name("王麻子"); customer1.setCust_profession("清洁工"); customer1.setCust_email("78754579846"); int row= sqlSession.insert("saveCustomer",customer1); int row2 = sqlSession.update("updateCustomerById",customer1); sqlSession.delete("deleteCustomerById",7) session.commit();123456789 四、MyBatis开发Dao1、原始的Dao开发方法1.1、创建CustomerDao接口类 123456789101112package com.lqg.dao;import com.lqg.domain.Customer;import java.util.List;public interface CustomerDao { public Customer findCustomerById(Long cust_id); public List<Customer> findAllCustomer(); public int saveCustomer(Customer customer);}1234567891011 1.2、创建CustomerDao接口类的实现类CustomerDaoImpl 123456789101112131415161718192021222324252627282930313233343536package com.lqg.daoImpl;import com.lqg.dao.CustomerDao;import com.lqg.domain.Customer;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import java.util.List;public class CustomerDaoImpl implements CustomerDao { private SqlSessionFactory sqlSessionFactory; public CustomerDaoImpl(SqlSessionFactory sqlSessionFactory){ this.sqlSessionFactory=sqlSessionFactory; } @Override public Customer findCustomerById(Long cust_id) { SqlSession sqlSession = sqlSessionFactory.openSession(); Customer customer = sqlSession.selectOne("queryCustomerById", 2); return customer; } @Override public List<Customer> findAllCustomer() { SqlSession sqlSession = sqlSessionFactory.openSession(); List<Customer> allCustomer = sqlSession.selectList("queryAllCustomer"); return allCustomer; } @Override public int saveCustomer(Customer customer) { SqlSession sqlSession = sqlSessionFactory.openSession(); int customer1=sqlSession.insert("saveCustomer",customer); return customer1; }}1234567891011121314151617181920212223242526272829303132333435 1.3、创建CustomerDao的测试类TestCustomerDao的测试类 123456789101112131415161718192021222324252627282930313233343536373839package com.lqg.test;import com.lqg.dao.CustomerDao;import com.lqg.daoImpl.CustomerDaoImpl;import com.lqg.domain.Customer;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class TestCustomerDao { private SqlSessionFactory sqlSessionFactory; public void init() throws IOException { System.out.println("init"); //1.创建一个SqlSessionFactoryBulider的类 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //2.加载SqlMapConfig.xml的配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //3.创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); }@Testpublic void test(){ //创建CustomerDao的接口编程 CustomerDao customerDao = new CustomerDaoImpl(this.sqlSessionFactory); //通过id查询用户,然后保存到customer中 Customer customer = customerDao.findCustomerById(2L); System.out.println(customer); List<Customer> allCustomer = customerDao.findAllCustomer(); System.out.println(allCustomer); }}1234567891011121314151617181920212223242526272829303132333435363738 2.Mapper动态代理2.1、Mapper动态代理开发的要求 namespace必须和Mapper接口类路径一致 id必须和Mapper接口方法名一致 parameterType必须和接口方法参数类型一致 resultType必须和接口方法返回值类型一致 2.2、先重新创建一张表 1234567CREATE TABLE tbl_employee{ id INT PRIMARY KEY auto_increment, last_name VARCHAR(255), gender CHAR(1), email VARCHAR(255)}123456 2.3、这是演示的结构图2.4、创建一个Employee的pojo类 123456789101112131415package com.lqg.mybatis.domain;import lombok.Getter;import lombok.Setter;import lombok.ToString;@Setter@Getter@ToStringpublic class Employee { private Integer id; private String lastName; private String gender; private String email;}1234567891011121314 2.5、创建MyBatis的核心配置文件 12345678910111213141516171819202122232425<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <!-- 和spring整合后 environments配置将废除 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理 --> <transactionManager type="JDBC" /> <!-- 数据库连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/lqg/mybatis/domain/EmployeeMapper.xml"/> </mappers></configuration>123456789101112131415161718192021222324 2.6、创建pojo的接口类 12345678package com.lqg.mybatis.dao;import com.lqg.mybatis.domain.Employee;public interface EmployeeMapper { public Employee getEmployeeById(Integer id);//方法名称为xml配置文件里面的对应操作语句的id名称}1234567 2.7、创建pojo的映射EmployeeMapper.xml 1234567891011121314151617<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace:命名空间,用于隔离sql语句,后续有重要内容 --> <!-- 1. namespace必须和Mapper接口类路径一致 2. id必须和Mapper接口方法名一致 3. parameterType必须和接口方法参数类型一致 4. resultType必须和接口方法返回值类型一致--><!--public Employee getEmployeeById(Integer id);--><mapper namespace="com.lqg.mybatis.dao.EmployeeMapper"> <select id="getEmployeeById" resultType="com.lqg.mybatis.domain.Employee"> select id,last_name lastName,gender,email from tbl_employee where id=#{id} </select></mapper>12345678910111213141516 2.8、最后编写MyBatisTest的测试类 12345678910111213141516171819202122232425262728293031323334package com.lqg.mybatis.test;import com.lqg.mybatis.dao.EmployeeMapper;import com.lqg.mybatis.domain.Employee;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;public class MyBatisTest { @Test public void test() throws IOException { //1.创建一个SqlSessionFactoryBulider的类 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //2.加载mybatis-config.xml的配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //3.创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); //4.创建SqlSession对象 SqlSession openSession = sqlSessionFactory.openSession(); //获取接口的实现类对象 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);//接口的字节码 Employee employee=mapper.getEmployeeById(1);//方法为接口当中的方法 System.out.println(employee); openSession.close(); }}123456789101112131415161718192021222324252627282930313233 2.9、查询效果如下 五、MyBatis的参数传递1.单个参数 可以接受基本类型,对象类型,集合类型的值。 MyBatis可直接使用这个参数,不需要经过任何处理。 2.多个参数 任意多个参数,都会被MyBatis重新包装成一个Map传入。 Map的key是param1,param2…,值就是参数的值示例3.@param命名参数 为参数使用@Param起一个名字 MyBatis就会将这些参数封装进map中,key就是我们自己指定的名字示例4.pojo 当这些参数属于我们业务POJO时,我们直接传递POJO示例5.Map我们也可以封装多个参数为map,直接传递示例6.参数传递源码分析 会把参数给放到一个数组当中 如果一个参数, 内部处理时,会自动把该参数范围 如果是多个参数,内部会做判断 判断是否有@param注解 如果没有: 没有注解的话, 就直接使用arg0 arg1…为key 放到map中并且还会以param1和param2…为key放一份到map中 如果有 如果有注解的话, 会使用注解当中的值,替换掉默认的arg0和arg1 使用@param中的值,做为key 放到一个map当中并且还会以param1和param2…为key放一份到map中 六、MyBatis的核心配置文件1、 properties:定义属性及读取属性文件 示例 1234 <properties resource="jdbc.properties"> <property name="jdbc.driver" value="com.mysql.jdbc.Driver"></property></properties>123 resource为资源文件,配置文件访问方法”${key名称}”,如访问数据库连接,如果配置了相同的property会先加载,resource里面的会把其覆盖掉 2、settings——这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为示例 123456 <!--全局信息配置,--> <settings> //配置打印sql信息 <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>12345 3、typeAliases——(定义别名,可以在使用时候省略掉前面一串路径) 1234567<typeAliases> <!--单个别名--> <!--<typeAlias type="domain.Customer" alias="Customer"></typeAlias>--> <!--批量定义别名,别名为类名--> <package name="domain"></package></typeAliases>123456 如果当前包类与子包类重名,会有异常,可以在类上使用注解@Alias(“别名”) 4、typeHandlers——(类型处理器)无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。JDK1.8之后实现全部的JSR310规范日期时间处理上,我们可以使用MyBatis基于JSR310(Date and Time API)编写的各种日期时间类型处理器。MyBatis3.4以前的版本需要我们手动注册这些处理器,以后的版本都是自动注册的 5、Plugins ——(插件)插件是MyBatis提供的一个非常强大的机制,MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。通过插件来修改MyBatis的一些核心行为。 6、Environments ——(数据库运行的环境)MyBatis可以配置多种环境,比如开发、测试和生产环境需要有不同的配置。每种环境使用一个environment标签进行配置并指定唯一标识符可以通过environments标签中的default属性指定一个环境的标识符来快速的切换环境Environment子标签transactionManager事务管理Type有以下取值JDBC使用JDBC 的提交和回滚设置,依赖于从数据源得到的连接来管理事务范围MANAGED不提交或回滚一个连接、让容器来管理事务的整个生命周期ManagedTransactionFactory自定义实现TransactionFactory接口type=全类名/别名dataSource数据源type有以下取值UNPOOLED不使用连接池UnpooledDataSourceFactoryPOOLED使用连接池PooledDataSourceFactoryJNDI在EJB 或应用服务器这类容器中查找指定的数据源自定义实现DataSourceFactory接口,定义数据源的获取方式实际开发实际开发中我们使用Spring管理数据源并进行事务控制的配置来覆盖上述配置 7、databaseIDProvider——(定义数据的厂商)MyBatis 可以根据不同的数据库厂商执行不同的语句。可以能过databaseIDProvider标签来进行设置 12345678910111213141516<databaseIdProvider type="DB_VENDOR"> <property name="MYSQL" value="mysql"/> <property name="DB2" value="db2"/> <property name="Oracle" value="oracle" /> <property name="SQL Server" value="sqlserver"/></databaseIdProvider>123456 示例1<mapper namespace="mapper.CustomerDao"> <select id="getCustomerWithID" resultType="Customer" databaseId="mysql"> //只有Mysql的数据库才能执行该语句 select * from customer where cust_id = #{id名称} and cust_name=#{值} </select></mapper> 123456 8、mappers——(加载映射文件)8.1、使用文件路径引入映射器 12 <mapper resource="domain/Customer.xml"></mapper> 1 8.2、使用mapper接口类路径,此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中 1234<mapper class=" " /> 如<mapper class="mapper.CustomerDao"></mapper>123 8.3、使用包名引入映射器指定包下的所有mapper接口、批量加载、此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中 12<package name=""/1 //加载对应包下面所有的文件 七、MyBatis的输出类型八、MyBatis【关联映射】1、MyBatis的多表连接1.1一对一 1.1.1设计表格:1234567891011121314151617181920--mysqlcreate table cards( cid int(5) primary key, cnum varchar(10));create table students( sid int(5) primary key, sname varchar(10), scid int(5), constraint scid_fk foreign key(scid) references cards(cid));insert into cards(cid,cnum) values(1,'111');insert into students(sid,sname,scid) values(1,'哈哈',1);select * from cards;select * from students;12345678910111213141516171819 1.1.2、实体类1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * 身份证(单方) * @author AdminTC */public class Card { private Integer id; private String num; public Card(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNum() { return num; } public void setNum(String num) { this.num = num; }}/** * 学生(单方) * @author AdminTC */public class Student { private Integer id; private String name; private Card card;//关联属性 public Student(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 1.1.3、映射文件由于我们有两个实体,因此我们会有两个映射文件Student映射文件 123456789101112<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="studentNamespace"> <resultMap type="zhongfucheng2.Student" id="studentMap"> <id property="id" column="sid"/> <result property="name" column="sname"/> </resultMap></mapper>1234567891011 Card映射文件 1234567891011121314<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cardNamespace"> <resultMap type="zhongfucheng2.Card" id="cardMap"> <id property="id" column="cid"/> <result property="num" column="cnum"/> </resultMap> </mapper>1234567891011select * from zhongfucheng.students s,zhongfucheng.cards c where c.cid = s.scid and sid=1;1 我来看一下查询结果:我们的实体与映射表中,Student实体是没有关联其他的字段的,仅仅是写出了该实体的自带的属性。 12345 <resultMap type="zhongfucheng2.Student" id="studentMap"> <id property="id" column="sid"/> <result property="name" column="sname"/> </resultMap>1234 明显地,我们Student是不能封装返回的结果,因此我们需要将关联属性进行关联起来! 1234567891011 <resultMap type="zhongfucheng2.Student" id="studentMap"> <id property="id" column="sid"/> <result property="name" column="sname"/> <!-- property写的是在Student实体中写关联字段的属性变量名称 resultMap写的是映射文件中的命名空间.id --> <association property="card" resultMap="cardNamespace.cardMap"/> </resultMap>12345678910 我们关联了以后,Student实体就能够封装返回的结果了 12345678910111213141516171819202122232425<!-- 因为使用多表联合查询, 那么查询结果中的列在对象中就没有对应的属性 所以需要我们自己去配置这些列与对象中的属性的映射关系 注意:并且需要给所有属性配置映射关系 --> <resultMap type="zhongfucheng2.Student" id="studentMap"> <!-- id子标签:用于配置主键的映射关系 ,这个id是下面的id column:查询结果中的列的列名 property:结果对象中的属性名 把列与属性之间关联起来:会把查询到的该列的值赋值给这个属性 <id property="id" column="sid"/> <result property="name" column="sname"/> <!-- property写的是在Student实体中写关联字段的属性变量名称 resultMap写的是映射文件中的命名空间.id --> <!-- 封装该对象的属性 与 查询语句结果的列的映射 关系 --> <association property="card" resultMap="cardNamespace.cardMap"/> </resultMap> <select id="findById" parameterType="int" resultMap="studentMap"> select * from zhongfucheng.students s,zhongfucheng.cards c where c.cid = s.scid and sid=#{id}; </select>123456789101112131415161718192021222324 1.1.4查询编号为1的学生信息【包括身份证编号】12345678910111213141516171819202122232425 public Student findById(int id) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ return sqlSession.selectOne("studentNamespace.findById", id); /* sqlSession.commit();*/ }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception { StudentDao studentDao = new StudentDao(); Student student = studentDao.findById(1); System.out.println(student.getId() + "----" + student.getName() + "----" + student.getCard().getNum()); }12345678910111213141516171819202122232425 这里写图片描述 2.1一对多 2.1.1设计数据库表123456789101112131415161718192021create table grades( gid int(5) primary key, gname varchar(10));create table students( sid int(5) primary key, sname varchar(10), sgid int(5), constraint sgid_fk foreign key(sgid) references grades(gid));insert into grades(gid,gname) values(1,'java');insert into students(sid,sname,sgid) values(1,'哈哈',1);insert into students(sid,sname,sgid) values(2,'呵呵',1);select * from grades;select * from students;1234567891011121314151617181920 2.1.2创建实体类12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package zhongfucheng2;import java.util.ArrayList;import java.util.List;/** * 学科(单方) * @author AdminTC */public class Grade { private Integer id; private String name; private List<Student> studentList = new ArrayList<Student>();//关联属性 public Grade(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Student> getStudentList() { return studentList; } public void setStudentList(List<Student> studentList) { this.studentList = studentList; }}package zhongfucheng2;/** * 学生(多方) * @author AdminTC */public class Student { private Integer id; private String name; private Grade grade;//关联属性 public Student(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 2.1.3映射文件SQL语句12345678910111213141516171819202122232425262728293031323334<mapper namespace="studentNamespace"> <resultMap type="zhongfucheng2.Student" id="studentMap"> <id property="id" column="sid"/> <result property="name" column="sname"/> </resultMap> <!--查询选修的java学科有多少位学生--> <!--由于我们只要查询学生的名字,而我们的实体studentMap可以封装学生的名字,那么我们返回studentMap即可,并不需要再关联到学科表--> <select id="findByGrade" parameterType="string" resultMap="studentMap"> select s.sname,s.sid from zhongfucheng.students s,zhongfucheng.grades g WHERE s.sgid=g.gid and g.gname=#{name}; </select></mapper><?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="gradeNamespace"> <resultMap type="zhongfucheng2.Grade" id="gradeMap"> <id property="id" column="gid"/> <result property="name" column="gname"/> </resultMap></mapper>123456789101112131415161718192021222324252627282930313233 2.1.4DAO12345678910111213141516171819202122232425public List<Student> findByGrade(String grade) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ return sqlSession.selectList("studentNamespace.findByGrade", grade); /* sqlSession.commit();*/ }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception { StudentDao studentDao = new StudentDao(); List<Student> student = studentDao.findByGrade("java"); for (Student student1 : student) { System.out.println(student1.getName()); } }123456789101112131415161718192021222324 1.3多对多 1.3.1数据库表12345678910111213141516171819202122232425262728293031create table students( sid int(5) primary key, sname varchar(10));create table courses( cid int(5) primary key, cname varchar(10));create table middles( msid int(5), mcid int(5), primary key(msid,mcid));insert into students(sid,sname) values(1,'哈哈');insert into students(sid,sname) values(2,'呵呵');insert into courses(cid,cname) values(1,'java');insert into courses(cid,cname) values(2,'android');insert into middles(msid,mcid) values(1,1);insert into middles(msid,mcid) values(1,2);insert into middles(msid,mcid) values(2,1);insert into middles(msid,mcid) values(2,2);select * from students;select * from courses;select * from middles;123456789101112131415161718192021222324252627282930 1.3.2 创建实体类12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667package cn.itcast.javaee.mybatis.many2many;import java.util.ArrayList;import java.util.List;/** * 课程(多方) * @author AdminTC */public class Course { private Integer id; private String name; private List<Student> studentList = new ArrayList<Student>();//关联属性 public Course(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Student> getStudentList() { return studentList; } public void setStudentList(List<Student> studentList) { this.studentList = studentList; }}package cn.itcast.javaee.mybatis.many2many;import java.util.ArrayList;import java.util.List;/** * 学生(多方) * @author AdminTC */public class Student { private Integer id; private String name; private List<Course> courseList = new ArrayList<Course>();//关联属性 public Student(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Course> getCourseList() { return courseList; } public void setCourseList(List<Course> courseList) { this.courseList = courseList; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 1.3.3映射文件1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="courseNamespace"> <resultMap type="cn.itcast.javaee.mybatis.many2many.Course" id="courseMap"> <id property="id" column="cid"/> <result property="name" column="cname"/> </resultMap> <!-- 查询哈哈选学了哪些课程 --> <select id="findAllByName" parameterType="string" resultMap="courseMap"> select c.cid,c.cname from students s inner join middles m on s.sid = m.msid inner join courses c on m.mcid = c.cid and s.sname = #{name} </select></mapper><?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="studentNamespace"> <resultMap type="cn.itcast.javaee.mybatis.many2many.Student" id="studentMap"> <id property="id" column="sid"/> <result property="name" column="sname"/> </resultMap> <select id="findAllByCourseName" parameterType="string" resultMap="studentMap"> select s.sname from students s inner join middles m on s.sid = m.msid inner join courses c on m.mcid = c.cid and c.cname = #{name} </select></mapper>12345678910111213141516171819202122232425262728293031323334353637383940414243444546 1.3.4创建DAO1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package cn.itcast.javaee.mybatis.many2many;import java.util.List;import org.apache.ibatis.session.SqlSession;import cn.itcast.javaee.mybatis.util.MybatisUtil;/** * 持久层 * @author AdminTC */public class StudentCourseDao { /** * 查询哈哈选学了哪些课程 * @param name 表示学生的姓名 */ public List<Course> findAllByName(String name) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList("courseNamespace.findAllByName",name); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 查询java课程有哪些学生选修 * @param name 表示学生的课程 */ public List<Student> findAllByCourseName(String name) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList("studentNamespace.findAllByCourseName",name); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentCourseDao dao = new StudentCourseDao(); List<Course> courseList = dao.findAllByName("哈哈"); System.out.print("哈哈选学了" + courseList.size()+"个课程,分别是:"); for(Course c : courseList){ System.out.print(c.getName()+" "); } System.out.println("\n-----------------------------------------------------"); List<Student> studentList = dao.findAllByCourseName("android"); System.out.println("选修了android课程的学生有"+studentList.size()+"个,分别是:"); for(Student s : studentList){ System.out.print(s.getName()+" "); } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 九、MyBatis的动态sql语句1.什么是动态sql:通过mybatis提供的各种标签方法实现动态拼接sql。 1、if标签需求:根据客户名和级别查询客户 12345<!--根据客户名和级别查询客户--><select id="queryCustomerWhere" parameterType="customer" resultType="customer"> select * from cst_customer where cust_name=#{cust_name} and cust_level=#{cust_level}</select> 1234 存在问题 有可能传入的名称或级别为空 可以使用if标签来进行判断 注意:test:放的是Boolean表达式 12345678910<select id="queryCustomerWhere" parameterType="customer" resultType="customer"> select * from cst_customer where <if test="cust_name !=null and cust_name=''"> cust_name=#{cust_name} </if> <if test="cust_level !=null and cust_name=''"> And cust_level=#{cust_name} </if></select> 123456789 如果前一个条件这后,后面就会多一个and执行就会报错 2、Where标签where标签可以自动添加where,同时可以处理sql语句中第一个and关键字 123456789101112<select id="queryCustomerWhere" parameterType="customer" resultType="customer"> select * from cst_custome <where> <if test="cust_name !=null and cust_name=''"> cust_name=#{cust_name} </if> <if test="cust_level !=null and cust_name=''"> And cust_level=#{cust_name} </if> </where></select> 1234567891011 去掉第一个前And 3、trim标签 prefix:设置前缀,在第一个条件之前加上一个前缀 prefixOerrides:条件前缀覆盖,把第一个条件之前的and变成空 suffix:设置后缀,在最后一个条件之后加上一个后缀 suffixOverrides:条件后缀覆盖,把最后一个条件之后的and变成空 123456789101112 <select id="getCustomer" resultType="domain.Customer"> select * from `customer` <trim prefix="where" prefixOverrides="and" suffixOverrides="" suffix="and"> <if test="name!=null and name!=''"> and cust_name=#{name} </if> <if test="profession!=null and profession!=''"> and cust_profession=#{profession} </if> </trim></select>1234567891011 DAO层现在我想根据学生的编号查询学生的信息和身份证信息! 由于该查询着重是查询学生的信息,于是我们在学生的映射文件中写SQL语句 按照需求,我们写出来的SQL语句是这样子的 4、choose标签choose用法基本和if一致 sqlsqlsql 注意:整个choose最终只会匹配一种情况 whenchoose标签:(只查满足条件的第一个,后面的条件都不执行) select * from customer 123456789101112<where> <choose> <when test="profession!=null and profession!=''"> cust_profession=#{profession} </when> <when test="name!=null and name!=''"> cust_name=#{name} </when> <otherwise>1=1</otherwise> //当都没有满足条件的时候,执行该默认语句 </choose></where>1234567891011 5、set标签6、foreach向sql传递数据或List,mybatis使用foreach解析,如下根据多个id查询用户信息查询sql:select * from user where id in(1,10,24)在pojo中定义list属性ids存储多个用户id,并添加getter/settter方法 123456@Getter@Setter@ToStringpublic class QueryVo{//包含其他的pojoprivate User user;private list<Integer> ids;12345 Mapper.xml文件 123456789101112131415<!--根据ids查询用户--><select id="queryUserByIds" parameterType="queryVo" resultType="user"> select * from user <where> <!--foreach标签,进行遍历--> <!--collection:遍历的集合,这里是queryVo的ids的属性值-> <!--遍历的项目,可以随便写,但是和后面的#{}里面要保持一致--> <!--open:在前面添加sql片段--> <!--separator:指定遍历元素之间的分隔符--> <foreach collection="ids" item="item" open="id IN("close =")" separator=","> #{item} </foreach> </where></select>1234567891011121314 7、bind用于绑定一个字符,并且取名 8、Sql片段使用include标签加载sql片段,refid是sql片段的id如果要使用别的Mapper.xml配置的sql片段,可以在refid前面加上对应的Mapper.xml的nameSpace如: 1234567891011121314151617<include refid="com.lqg.mybatis.mapper.OrderMapper.userFirlds"/>1<select id="queryCustomerWhere" parameterType="customer" resultType="customer"> select <include refid="userFirlds"/> from cst_custome <where> <if test="cust_name !=null and cust_name=''"> cust_name=#{cust_name} </if> <if test="cust_level !=null and cust_name=''"> And cust_level=#{cust_name} </if> </where></select> <!--声明sql片段--><sql id="userFieleds"> cust_id,cust_name,cust_level </sql>]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>MyBatis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二、MyBatis入门示例]]></title>
<url>%2F2019%2F08%2F25%2F%E4%BA%8C%E3%80%81MyBatis%E5%85%A5%E9%97%A8%E7%A4%BA%E4%BE%8B%2F</url>
<content type="text"><![CDATA[二、MyBatis入门示例 在本篇博客中,我们来一起完成MyBatis的入门示例 准备数据库和表12345678910111213141516DROP TABLE student;CREATE TABLE student( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), gender VARCHAR(10), birthday DATE );INSERT INTO student (name,gender,birthday) VALUES ('波多结衣','female','1995-12-11');INSERT INTO student (name,gender,birthday) VALUES ('波少结衣','female','1996-11-12');INSERT INTO student (name,gender,birthday) VALUES ('杉原杏璃','female','1997-10-13');INSERT INTO student (name,gender,birthday) VALUES ('佐佐木希','female','1998-09-14');INSERT INTO student (name,gender,birthday) VALUES ('伊藤梅子','female','1999-08-15');12345678910111213141516 我们建立数据库mb,并创建一张表student并为其插入数据。 创建JavaBean1234567891011121314151617181920212223242526272829303132333435363738394041package cn.com.helloworld;import java.util.Date;public class Student { private int id; private String name; private String gender; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", birthday=" + birthday + "]"; }} 请注意:将JavaBean中的字段与数据库中表中的字段保持一致 导入MyBatis相关jar包请下载MyBatis开发所需jar包并存放至工程的lib目录。 SqlMapConfig.xml在有了数据库和JavaBean之后我们来编写MyBatis的全局配置文件SqlMapConfig.xml 12345678910111213141516<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mb?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments></configuration>12345678910111213141516 在该配置文件中配置由MyBatis所采用的事务和数据库连接池 StudentMapper.xml刚才我们编写了MyBatis的全局配置文件SqlMapConfig.xml,现在我们来编写与JavaBean相关的配置文件StudentMapper.xml 123456<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="student"></mapper>123456 我们在该配置文件中添加标签并设置其namespace为student。 再将StudentMapper.xml配置到SqlMapConfig.xml,代码如下: 123456789101112131415161718<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mb?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="sqlmap/StudentMapper.xml" /> </mappers></configuration>123456789101112131415161718 请参见代码第15—17行 CRUD操作在完成了之上的准备工作后,我们来利用MyBatis实现简单的增删改查。 我们先来做一个最简单的例子:依据Stundet的id查询学生信息 首先在映射文件StudentMapper.xml中写sql语句: 12345678910<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="student"> <select id="findStudentById" parameterType="int" resultType="cn.com.helloworld.Student"> SELECT * FROM student WHERE id=#{value} </select></mapper>12345678910 在该xml文件中为我们的需求写了一个sql语句,请注意 id标识该sql语句的唯一性,因为之后随着功能的扩展在该xml文件中会有许多sql语句。其实,类似于StudentMapper.xml这样的mapper.xml文件中每一个sql语句都对应一个MappedStatement对象,sql语句的id即是MappedStatement的id。 parameterType表示输入参数类型。此处我们要依据id查询学生,那么输入参数就是一个int类型的数字 resultType表示查询结果的返回类型。在此,我们想得到一个Student对象,所以将resultType设置为cn.com.helloworld.Student #{ }表示占位符,用于接收输入参数。输入参数的类型可以是简单类型,pojo、HashMap。如果输入参数是简单类型那么#{}的括号中可以写成value或其它名称。 在完成了映射文件的编码之后,我们再来书写Java代码 1234567891011121314151617181920212223242526/** * 本文作者:谷哥的小弟 * 博客地址:http://blog.csdn.net/lfdfhl */package cn.com.helloworld;import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;public class CRUDTest { @Test public void findStudentById() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Student student = sqlSession.selectOne("student.findStudentById", 1); System.out.println(student); sqlSession.close(); }} 代码详解如下: 获取MyBatis的全局配置文件SqlMapConfig.xml,请参见代码第18—19行 利用全局配置文件创建SqlSessionFactory,请参见代码第20行 利用SqlSessionFactory创建SqlSession,请参见代码第21行 利用SqlSession调用其selectOne()方法查询一条学生信息,请参见代码第22行。请注意该方法参数:第一个参数用于标识一条sql语句,其构成为:映射文件的namespace+”.”+MappedStatement的id(即sql语句的id);第二参数是需要传递给sql语句的输入参数。 关闭SqlSession,释放资源;请参见代码第24行 输出结果如下: Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995] 至此,我们走完了一个利用MyBatis查询数据的完整流程。 刚才这个例子是查询出来了单条记录,如果要查询多条记录又该怎么做呢?比如查询出学生名字中带有”结”这个字的所有学生,请看如下代码: 123<select id="findStudentByName" parameterType="java.lang.String" resultType="cn.com.helloworld.Student"> SELECT * FROM student WHERE name LIKE '%${value}%'</select> 在该映射文件中采用${ }表示拼接,它所接收的输入参数类型可以是简单类型,pojo,HashMap。如果接收简单类型,${}中只能写成value。当${}接收pojo对象值时可通过OGNL读取对象中的属性值;即利用属性.属性.属性…的方式获取对象属性值 在完成映射文件的编写之后,我们再来看Java代码: 123456789101112@Test public void findStudentByName() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<Student> list = sqlSession.selectList("student.findStudentByName", "结"); for(Student student:list){ System.out.println(student); } sqlSession.close(); } 在此利用了qlSession.selectList( )方法返回一个查询后的集合。 输出结果如下: Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995]Student [id=2, name=波少结衣, gender=female, birthday=Tue Nov 12 00:00:00 CST 1996] 在完成查询操作后,我们向数据库插入一条新数据,并得到新数据被插入到数据库后它的主键值。 123456<insert id="insertStudent" parameterType="cn.com.helloworld.Student"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO student (name,gender,birthday) value (#{name},#{gender},#{birthday}) </insert>123456 我们在标签中使用了标签获取插入数据的主键并将其设置到Student对象中. SELECT LAST_INSERT_ID():得到insert记录的主键值,只适用与自增主键 keyProperty:用于指明将查询到的主键值设置到parameterType指定的对象的哪个属性 order:表示SELECT LAST_INSERT_ID()相对于insert语句的执行顺序。在该例子中用AFTER表示执行完该insert语句后再执行SELECT LAST_INSERT_ID() resultType:指定SELECT LAST_INSERT_ID()的结果的类型 123456789101112131415@Test public void insertStudent() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Student student=new Student(); student.setName("右右木希"); student.setGender("female"); student.setBirthday(new Date()); sqlSession.insert("student.insertStudent",student); sqlSession.commit(); sqlSession.close(); System.out.println(""+student.getId()); } 代码解析如下: 利用sqlSession.insert()将数据插入数据库,请参见代码第11行 利用sqlSession.commit()提交事务,请参见代码第12行 获取到新插入数据的主键值,请参见代码第14行 继续来看删除数据的操作 123<delete id="deleteStudent" parameterType="java.lang.Integer"> DELETE FROM student where id=#{id}</delete>123 Java代码如下: 12345678910@Test public void deleteStudent() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("student.deleteStudent", 1); sqlSession.commit(); sqlSession.close(); }12345678910 最后来瞅瞅更新操作 123<update id="updateStudent" parameterType="cn.com.helloworld.Student"> UPDATE student set name=#{name},gender=#{gender},birthday=#{birthday} where id=#{id} </update>123 Java代码如下: 123456789101112131415@Test public void updateStudent() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Student student=new Student(); student.setId(3); student.setName("中中木希"); student.setGender("female"); student.setBirthday(new Date()); sqlSession.update("student.updateStudent", student); sqlSession.commit(); sqlSession.close(); }123456789101112131415 嗯哼,至此我们关于MyBatis的入门示例就已经全部完成了。 项目结构图如下所示:]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>MyBatis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[一、MyBatis概述]]></title>
<url>%2F2019%2F08%2F25%2F%E4%B8%80%E3%80%81MyBatis%E6%A6%82%E8%BF%B0%2F</url>
<content type="text"><![CDATA[MyBatis简介 MyBatis原本是apache的一个开源项目iBatis, 2010年该项目由apache software foundation 迁移到了google code并改名为MyBatis 。2013年11月MyBatis又迁移到Github。 The MyBatis SQL mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools. MyBatis是一个优秀的持久层框架,它对JDBC操作数据库的过程进行了封装,使开发者只需要关注SQL本身,而不需要开发人员花费大量的精力去处理例如注册驱动、创建connection、创建statement、手动设置参数等JDBC操作。 Mybatis通过xml或注解的方式将要执行的各种statement配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由MyBatis框架执行sql并将结果映射成java对象并返回。 更多介绍,敬请参见MyBatis官方网站:http://www.mybatis.org/mybatis-3/ MyBatis框架1、SqlMapConfig.xml是MyBatis的全局配置文件,它配置了MyBatis的运行环境等信息。 2、mapper.xml是sql映射文件,它配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载 3、通过MyBatis配置信息构造SqlSessionFactory(会话工厂) 4、由会话SqlSessionFactory(工厂)创建SqlSession(会话)操作数据库 5、MyBatis底层自定义Executor(执行器)接口用于执行数据库操作,该接口有两个实现:基本执行器和缓存执行器。 6、MappedStatement是MyBatis的底层封装对象,它封装了操作数据库的sql语句,输入参数,输出结果等信息。mapper.xml文件中每一个sql语句对应一个MappedStatement对象,sql语句的id即是MappedStatement的id。 7、MappedStatement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过MappedStatement在执行sql前将输入的java对象映射至sql中 8、MappedStatement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过MappedStatement在执行sql后将输出结果映射至java对象中 MyBatis开发环境在利用MyBatis开发前,请移步MyBatis官网下载开发所有的jar包、开发指南,说明文档等资料。]]></content>
<categories>
<category>后台</category>
</categories>
<tags>
<tag>MyBatis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[三、Spring Boot多环境配置详解]]></title>
<url>%2F2019%2F08%2F25%2F%E4%B8%89%E3%80%81Spring-Boot%E5%A4%9A%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3%2F</url>
<content type="text"><![CDATA[Spring Boot多环境配置详解一. 多环境配置的好处: 1.不同环境配置可以配置不同的参数 2.便于部署,提高效率,减少出错 二. Properties多环境配置 配置激活选项 spring.profiles.active=dev 2.添加其他配置文件 三.YAML多环境配置 1.配置激活选项 spring: profiles:active: dev 2.在配置文件添加三个英文状态下的短横线即可区分 — spring: profiles: dev四.两种配置方式的比较 1. Properties配置多环境,需要添加多个配置文件,YAML只需要一个配件文件 2.书写格式的差异,yaml相对比较简洁,优雅 \3. YAML的缺点:不能通过@PropertySource注解加载。如果需要使用@PropertySource注解的方式加载值,那就要使用properties文件。 五.如何使用 java -jar myapp.jar –spring.profiles.active=dev]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[《WEB开发-HEXO博客搭建》第一章Hexo的简介与安装]]></title>
<url>%2F2019%2F08%2F25%2F%E3%80%8AWEB%E5%BC%80%E5%8F%91-HEXO%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0Hexo%E7%9A%84%E7%AE%80%E4%BB%8B%E4%B8%8E%E5%AE%89%E8%A3%85%2F</url>
<content type="text"><![CDATA[《WEB开发-HEXO博客搭建》第1章 Hexo博客搭建Hexo官方:https://hexo.io/Hexo官方(中文):https://hexo.io/zh-cn/Node.js官方网站:https://nodejs.org/en/Node.js官方文档:https://nodejs.org/en/docs/Node.js安装文档:https://nodejs.org/en/download/package-manager/ 1.1 Hexo简介Hexo是一个快速, 简洁且高效的博客框架. 让上百个页面在几秒内瞬间完成渲染. Hexo支持Github Flavored Markdown的所有功能, 甚至可以整合Octopress的大多数插件. 并自己也拥有强大的插件系统。 1.2 node.js安装Hexo是基于node.js的,所以我们在安装它之前需要用到npm安装工具,这个工具是 node.js 安装包的工具,所以,我们先要安装 node.js。笔者是用的Windows 64位的,到node.js下载安装包。 图1 下载后直接安装就可以啦,和普通的软件没有什么大的区别,所有笔者就不赘述了。 1.3 GitHub账户创建及客户端安装关于git账户创建及客户端下载安装等可参看笔者的博客,笔者在这里就不在赘述了。GitHub官网:https://github.com/Git和Github的使用:https://blog.csdn.net/u013162035/article/details/78476880Git下载:https://git-scm.com/downloadsGit安装:https://blog.csdn.net/u013162035/article/details/78464161 在github网页上创建一个以username.github.io命名的repositories,此时username为自己github的账号名称。 1.4安装hexo使用npm安装Hexo,输入以下命令: 1$ npm install hexo-cli -g 1.5创建Blog笔者在D盘下新建一个blog的文件夹,然后进入blog文件夹,单击右键打开git bash。1. 创建一个叫blog网站$ hexo init 如果没有进入blog文件夹, 就会在当前目录进行初始化。这是初始化命令就要加blog。$ hexo init blog 如果后面跟了名子就会创建目录并在目录进行初始化操作, 以这个名子为目录名。2. 我们进入创建的blog目录里. 并运行该服务$ npm install $ hexo server 【注】hexo命令$ hexo install 3. 测试网页打开浏览器, 在地址栏输入http://localhost:4000/可以看到我们刚刚创建的blog首页 4.修改blog目录下的_config.yml配置文件将网站自部署到Github上$ vim _config.yml 添加如下内容 123git repo: git@github.com:用户名/用户名.github.io.gitbranch: master 【注】在type前面需要增加两个空格,在type的冒号后面需要增加一个空格。请保持代码风格一致,否则会出现错误或是不正确的问题。5.安装部署使用到的git插件在这里我们使用的是git源码管理工具,所以,我需要安装git包进行部署,安装这个插件才能使用git进行自动部署。 $ npm install hexo-deployer-git -save 在接下来,我们将要生成网站了,首先清理一下缓存。$hexo clean 6.进行生成网站当我们部署网站前,需要先生成静态网站。它会自动在目录下创建public的目录, 并将新生成的网页存放在这个目录里。 $ hexo g或hexo generate 7.进行自动部署网站注意部署前需要重新生成网站, 每一次修改后都需要重新生成网站并进行部署,生成网站前第6步。 $ hexo d或hexo deploy 如果在部署出现错误信息如果下: 请参考第5步,需要安装git插件ERROR Deployer not found: git以上两步可以使用一步就可以搞定: $hexo g -d 【注】上述的部署指令中hexo deploy可以换成hexo server,两者的区别在于,前者是将博客部署到远程的Github上,而后者是运行在本地,通过http://localhost:4000在浏览器中访问。后者是为了调试配置方便而使用,但是最终本地博客还是需要hexo deploy指令将其部署至Github上。接下来就是查看是否成功啦。打开浏览器输入IP地址。 图2 表明创建成功了。]]></content>
<categories>
<category>Hexo</category>
</categories>
<tags>
<tag>Hexo</tag>
</tags>
</entry>
<entry>
<title><![CDATA[《WEB开发-HEXO博客搭建》第二章Hexo的博客配置]]></title>
<url>%2F2019%2F08%2F25%2F%E3%80%8AWEB%E5%BC%80%E5%8F%91-HEXO%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0Hexo%E7%9A%84%E5%8D%9A%E5%AE%A2%E9%85%8D%E7%BD%AE%2F</url>
<content type="text"><![CDATA[《WEB开发-HEXO博客搭建》第2章 Hexo博客配置Hexo官方Hexo官方(中文)Hexo主题Next 主题 图1 2.1 Hexo页面添加及设置默认有些页面是没有的,需要手动添加,进入博客文件夹,打开Git bash。 123$hexo new page "categories"$hexo new page "tags" $hexo new page "about" 编辑 tags/index.md 和categories/index.md和about/index.md分别添加如下内容: 12type: "categories"layout: "categories" 1234type: "tags"layout: "tags"type: "about"layout: "about" 主题的 _config.yml 文件中的 menu 中进行匹配。 123456menu: Home: / //主页 Archives: /archives //分类 categories: /categories //归档 tags: /tags //标签 about: /about //关于 2.2添加评论功能来必力官网: https://livere.com没有账号的注册账号,打开来必力官网: https://livere.com,点击上方的安装,选择免费的city版本。 图2 图3 点击【申请获得代码】,进入下一步操作。复制其中的uid字段。 123456789101112131415161718<!-- 来必力City版安装代码 --><div id="lv-container" data-id="city" data-uid="MTAyMC8zNzMzMC8xMzg2NA=="> <script type="text/javascript"> (function(d, s) { var j, e = d.getElementsByTagName(s)[0]; if (typeof LivereTower === 'function') { return; } j = d.createElement(s); j.src = 'https://cdn-city.livere.com/js/embed.dist.js'; j.async = true; e.parentNode.insertBefore(j, e); })(document, 'script'); </script><noscript> 为正常使用来必力评论功能请激活JavaScript</noscript></div><!-- City版安装代码已完成 --> 图4 打开主题目录下的 blog/themes/某个主题/_config.yml 配置文件,定位到 livere_uid 字段,粘贴上刚刚复制的UID。 至此,大功告成。效果展示测试评论如图所示: 图5 2.3统计配置笔者使用的是不蒜子统计注意:此特性在版本 5.0.1 中引入,要使用此功能请确保所使用的 NexT 版本在此之后。 全局设置 编辑主题配置文件中的busuanzi_count的配置项。当enable: true时,代表开启全局开关。若site_uv、site_pv、page_pv的值均为false时,不蒜子仅作记录而不会在页面上显示。 站点UV设置当site_uv: true时,代表在页面底部显示站点的UV值。site_uv_header和site_uv_footer为自定义样式配置,相关的值留空时将不显示,可以使用(带特效的)font-awesome。显示效果为[site_uv_header]UV值[site_uv_footer]。 //效果:本站访客数12345人次site_uv: truesite_uv_header: 本站访客数site_uv_footer: 人次 站点PV设置当site_pv: true时,代表在页面底部显示站点的PV值。site_pv_header和site_pv_footer为自定义样式配置,相关的值留空时将不显示,可以使用(带特效的)font-awesome。显示效果为[site_pv_header]PV值[site_pv_footer]。 //效果:本站总访问量12345次site_pv: truesite_pv_header: 本站总访问量site_pv_footer: 次 单页面PV配置当page_pv: true时,代表在文章页面的标题下显示该页面的PV值(阅读数)。page_pv_header和page_pv_footer为自定义样式配置,相关的值留空时将不显示,可以使用(带特效的)font-awesome。显示效果为[page_pv_header]PV值[page_pv_footer]。 //效果:本文总阅读量12345次page_pv: truepage_pv_header: 本文总阅读量page_pv_footer: 次 2.4搜索配置笔者使用的是Local Search,添加百度/谷歌/本地 自定义站点内容搜索。一、安装 hexo-generator-searchdb在站点的根目录下执行以下命令: $ npm install hexo-generator-searchdb —save 二、编辑站点配置文件,新增以下内容到任意位置 12345search: path: search.xml field: post format: html limit: 10000 三、编辑主题配置文件,启用本地搜索功能 123# Local searchlocal_search: enable: true]]></content>
<categories>
<category>Hexo</category>
</categories>
<tags>
<tag>Hexo</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Hexo博客之博客美化]]></title>
<url>%2F2019%2F08%2F24%2FHexo%E5%8D%9A%E5%AE%A2%E4%B9%8B%E5%8D%9A%E5%AE%A2%E7%BE%8E%E5%8C%96%2F</url>
<content type="text"><![CDATA[Hexo 博客优化之博客美化(看板娘/鼠标点击爱心字体烟花爆炸/自定义鼠标指针样式/彩色滚动变换字体/背景音乐/网页标题恶搞/动态线条/人体时钟挂件/雪花飘落/背景动态彩带/背景代码雨……)转载自:链接:https://blog.csdn.net/qq_36759224/article/details/85420403 本文将讲述一些Hexo博客的美化,不同主题可能方法有些不同(本文以作者 luuman 的 spfk 主题和作者 xaoxuu 的 Material X 主题为例)实际效果欢迎访问我的博客:https://www.itrhx.com/ 进行查看,本文章会不定时进行更新。文章涉及有关参考资料、教程、链接如有侵权请联系我删除! 欢迎关注我的专栏:《个人博客搭建:Hexo+Github Pages》,从搭建到美化一条龙,帮你解决 Hexo 常见问题! 推荐阅读:《Hexo 博客优化之实用功能添加(评论系统/字数统计/阅读时长/网站运行时间/百度统计/RSS订阅/Fork me on GitHub/更改本地预览端口号…)》 文章目录 ● 添加卡通人物(看板娘) ● 添加鼠标点击爱心效果 ● 添加鼠标点击显示字体效果 ● 添加鼠标点击烟花爆炸效果 ● 自定义鼠标指针样式 ● 添加彩色滚动变换字体 ● 添加背景音乐 ● 浏览器网页标题恶搞 ● 背景添加动态线条效果 ● 添加人体时钟等有趣的挂件 ● 添加网站雪花飘落效果 ● 添加背景动态彩带效果 ● 添加背景代码雨特效 未完待续…… ● 添加卡通人物(看板娘)我在逛别人博客的时候偶然发现右下角居然有一个萌萌的卡通人物,还能根据你鼠标位置摇头,瞬间被吸引到了,赶紧也给自己博客添加一个吧!点击此处进入该项目地址 输入如下命令获取 live2d : 12$ npm install --save hexo-helper-live2d 1 输入以下命令,下载相应的模型,将 packagename 更换成模型名称即可,更多模型选择请点击此处,各个模型的预览请访问原作者的博客 12$ npm install packagename1 打开站点目录下的 _config.yml 文件,添加如下代码: 123456789101112live2d: enable: true scriptFrom: local model: use: live2d-widget-model-haruto #模型选择 display: position: right #模型位置 width: 150 #模型宽度 height: 300 #模型高度 mobile: show: false #是否在手机端显示1234567891011 设置好过后我们就拥有了一个卡通人物 ● 添加鼠标点击爱心效果在 /themes/hexo-theme-spfk/source/js 下新建文件 love.js,在 love.js 文件中添加以下代码: 12!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 500%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);1 在 \themes\hexo-theme-spfk\layout\layout.ejs 文件末尾添加以下代码: 123<!-- 页面点击小红心 --><script type="text/javascript" src="/js/love.js"></script>12 完成以上操作后,当我们点击鼠标的时候就可以看见爱心的特效了 ● 添加鼠标点击显示字体效果在 /themes/hexo-theme-spfk/source/js 下新建文件 click_show_text.js,在 click_show_text.js 文件中添加以下代码: 12345678910111213141516171819202122232425262728293031323334var a_idx = 0;jQuery(document).ready(function($) { $("body").click(function(e) { var a = new Array ("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善"); var $i = $("<span/>").text(a[a_idx]); a_idx = (a_idx + 1) % a.length; var x = e.pageX, y = e.pageY; $i.css({ "z-index": 5, "top": y - 20, "left": x, "position": "absolute", "font-weight": "bold", "color": "#FF0000" }); $("body").append($i); $i.animate({ "top": y - 180, "opacity": 0 }, 3000, function() { $i.remove(); }); }); setTimeout('delay()', 2000);});function delay() { $(".buryit").removeAttr("onclick");}123456789101112131415161718192021222324252627282930313233 其中的社会主义核心价值观可以根据你自己的创意替换为其他文字,然后在 \themes\hexo-theme-spfk\layout\layout.ejs 文件末尾添加以下代码: 123<!--单击显示文字--><script type="text/javascript" src="/js/click_show_text.js"></script>12 最终实现效果如下: ● 添加鼠标点击烟花爆炸效果在 \themes\material-x\source\js 目录下新建一个 fireworks.js 的文件,里面写入以下代码: 12"use strict";function updateCoords(e){pointerX=(e.clientX||e.touches[0].clientX)-canvasEl.getBoundingClientRect().left,pointerY=e.clientY||e.touches[0].clientY-canvasEl.getBoundingClientRect().top}function setParticuleDirection(e){var t=anime.random(0,360)*Math.PI/180,a=anime.random(50,180),n=[-1,1][anime.random(0,1)]*a;return{x:e.x+n*Math.cos(t),y:e.y+n*Math.sin(t)}}function createParticule(e,t){var a={};return a.x=e,a.y=t,a.color=colors[anime.random(0,colors.length-1)],a.radius=anime.random(16,32),a.endPos=setParticuleDirection(a),a.draw=function(){ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.fillStyle=a.color,ctx.fill()},a}function createCircle(e,t){var a={};return a.x=e,a.y=t,a.color="#F00",a.radius=0.1,a.alpha=0.5,a.lineWidth=6,a.draw=function(){ctx.globalAlpha=a.alpha,ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.lineWidth=a.lineWidth,ctx.strokeStyle=a.color,ctx.stroke(),ctx.globalAlpha=1},a}function renderParticule(e){for(var t=0;t<e.animatables.length;t++){e.animatables[t].target.draw()}}function animateParticules(e,t){for(var a=createCircle(e,t),n=[],i=0;i<numberOfParticules;i++){n.push(createParticule(e,t))}anime.timeline().add({targets:n,x:function(e){return e.endPos.x},y:function(e){return e.endPos.y},radius:0.1,duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule}).add({targets:a,radius:anime.random(80,160),lineWidth:0,alpha:{value:0,easing:"linear",duration:anime.random(600,800)},duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule,offset:0})}function debounce(e,t){var a;return function(){var n=this,i=arguments;clearTimeout(a),a=setTimeout(function(){e.apply(n,i)},t)}}var canvasEl=document.querySelector(".fireworks");if(canvasEl){var ctx=canvasEl.getContext("2d"),numberOfParticules=30,pointerX=0,pointerY=0,tap="mousedown",colors=["#FF1461","#18FF92","#5A87FF","#FBF38C"],setCanvasSize=debounce(function(){canvasEl.width=2*window.innerWidth,canvasEl.height=2*window.innerHeight,canvasEl.style.width=window.innerWidth+"px",canvasEl.style.height=window.innerHeight+"px",canvasEl.getContext("2d").scale(2,2)},500),render=anime({duration:1/0,update:function(){ctx.clearRect(0,0,canvasEl.width,canvasEl.height)}});document.addEventListener(tap,function(e){"sidebar"!==e.target.id&&"toggle-sidebar"!==e.target.id&&"A"!==e.target.nodeName&&"IMG"!==e.target.nodeName&&(render.play(),updateCoords(e),animateParticules(pointerX,pointerY))},!1),setCanvasSize(),window.addEventListener("resize",setCanvasSize,!1)}"use strict";function updateCoords(e){pointerX=(e.clientX||e.touches[0].clientX)-canvasEl.getBoundingClientRect().left,pointerY=e.clientY||e.touches[0].clientY-canvasEl.getBoundingClientRect().top}function setParticuleDirection(e){var t=anime.random(0,360)*Math.PI/180,a=anime.random(50,180),n=[-1,1][anime.random(0,1)]*a;return{x:e.x+n*Math.cos(t),y:e.y+n*Math.sin(t)}}function createParticule(e,t){var a={};return a.x=e,a.y=t,a.color=colors[anime.random(0,colors.length-1)],a.radius=anime.random(16,32),a.endPos=setParticuleDirection(a),a.draw=function(){ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.fillStyle=a.color,ctx.fill()},a}function createCircle(e,t){var a={};return a.x=e,a.y=t,a.color="#F00",a.radius=0.1,a.alpha=0.5,a.lineWidth=6,a.draw=function(){ctx.globalAlpha=a.alpha,ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.lineWidth=a.lineWidth,ctx.strokeStyle=a.color,ctx.stroke(),ctx.globalAlpha=1},a}function renderParticule(e){for(var t=0;t<e.animatables.length;t++){e.animatables[t].target.draw()}}function animateParticules(e,t){for(var a=createCircle(e,t),n=[],i=0;i<numberOfParticules;i++){n.push(createParticule(e,t))}anime.timeline().add({targets:n,x:function(e){return e.endPos.x},y:function(e){return e.endPos.y},radius:0.1,duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule}).add({targets:a,radius:anime.random(80,160),lineWidth:0,alpha:{value:0,easing:"linear",duration:anime.random(600,800)},duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule,offset:0})}function debounce(e,t){var a;return function(){var n=this,i=arguments;clearTimeout(a),a=setTimeout(function(){e.apply(n,i)},t)}}var canvasEl=document.querySelector(".fireworks");if(canvasEl){var ctx=canvasEl.getContext("2d"),numberOfParticules=30,pointerX=0,pointerY=0,tap="mousedown",colors=["#FF1461","#18FF92","#5A87FF","#FBF38C"],setCanvasSize=debounce(function(){canvasEl.width=2*window.innerWidth,canvasEl.height=2*window.innerHeight,canvasEl.style.width=window.innerWidth+"px",canvasEl.style.height=window.innerHeight+"px",canvasEl.getContext("2d").scale(2,2)},500),render=anime({duration:1/0,update:function(){ctx.clearRect(0,0,canvasEl.width,canvasEl.height)}});document.addEventListener(tap,function(e){"sidebar"!==e.target.id&&"toggle-sidebar"!==e.target.id&&"A"!==e.target.nodeName&&"IMG"!==e.target.nodeName&&(render.play(),updateCoords(e),animateParticules(pointerX,pointerY))},!1),setCanvasSize(),window.addEventListener("resize",setCanvasSize,!1)};1 然后在 \themes\material-x\layout\layout.ejs 文件中写入以下代码: 1234<canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> <script type="text/javascript" src="/js/fireworks.js"></script>123 最终效果: ● 自定义鼠标指针样式在 \themes\material-x\source\less_base.less 文件 body 样式里写入如下代码: 1234567body { cursor: url(https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.1.6/images/mouse.cur),auto; background-color: @theme_background; ...... ......}123456 鼠标指针可以用 Axialis CursorWorkshop 这个软件自己制作,不同主题具体放的文件有所不同,确保在博客主体 body 的 CSS 文件中即可,其中的鼠标指针链接可替换成自己的,首先尝试加载https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.1.6/images/mouse.cur ,如果该文件不存在或由于其他原因无效,那么 auto 会被使用,也就是自动默认效果,图片格式为.ico、.ani、.cur,建议使用.cur,如果使用.ani或者其他格式无效,原因是浏览器兼容问题,请阅读参考文档或者参考以下兼容表: 浏览器 最低版本 格式 Internet Explorer 6.0 .cur / .ani Firefox (Gecko), Windows and Linux 1.5 (1.8) .cur / .png / .gif / .jpg Firefox (Gecko) 4.0 (2.0) .cur / .png / .gif / .jpg / .svg Opera — — Safari (Webkit) 3.0 (522-523) .cur / .png / .gif / .jpg 拓展阅读:《CSS 鼠标样式 cursor属性》 (By:歪脖先生的博客) ● 添加彩色滚动变换字体在你想要添加彩色滚动变换字体的地方写入以下代码即可,其中文字可自行更改: 12345678910111213141516171819202122232425262728293031323334353637383940414243<div id="binft"></div> <script> var binft = function (r) { function t() { return b[Math.floor(Math.random() * b.length)] } function e() { return String.fromCharCode(94 * Math.random() + 33) } function n(r) { for (var n = document.createDocumentFragment(), i = 0; r > i; i++) { var l = document.createElement("span"); l.textContent = e(), l.style.color = t(), n.appendChild(l) } return n } function i() { var t = o[c.skillI]; c.step ? c.step-- : (c.step = g, c.prefixP < l.length ? (c.prefixP >= 0 && (c.text += l[c.prefixP]), c.prefixP++) : "forward" === c.direction ? c.skillP < t.length ? (c.text += t[c.skillP], c.skillP++) : c.delay ? c.delay-- : (c.direction = "backward", c.delay = a) : c.skillP > 0 ? (c.text = c.text.slice(0, -1), c.skillP--) : (c.skillI = (c.skillI + 1) % o.length, c.direction = "forward")), r.textContent = c.text, r.appendChild(n(c.prefixP < l.length ? Math.min(s, s + c.prefixP) : Math.min(s, t.length - c.skillP))), setTimeout(i, d) } var l = "", o = ["青青陵上柏,磊磊涧中石。", "人生天地间,忽如远行客。","斗酒相娱乐,聊厚不为薄。", "驱车策驽马,游戏宛与洛。","洛中何郁郁,冠带自相索。","长衢罗夹巷,王侯多第宅。","两宫遥相望,双阙百余尺。","极宴娱心意,戚戚何所迫?"].map(function (r) { return r + "" }), a = 2, g = 1, s = 5, d = 75, b = ["rgb(110,64,170)", "rgb(150,61,179)", "rgb(191,60,175)", "rgb(228,65,157)", "rgb(254,75,131)", "rgb(255,94,99)", "rgb(255,120,71)", "rgb(251,150,51)", "rgb(226,183,47)", "rgb(198,214,60)", "rgb(175,240,91)", "rgb(127,246,88)", "rgb(82,246,103)", "rgb(48,239,130)", "rgb(29,223,163)", "rgb(26,199,194)", "rgb(35,171,216)", "rgb(54,140,225)", "rgb(76,110,219)", "rgb(96,84,200)"], c = { text: "", prefixP: -s, skillI: 0, skillP: 0, direction: "forward", delay: a, step: g }; i() }; binft(document.getElementById('binft')); </script>123456789101112131415161718192021222324252627282930313233343536373839404142 最终效果: ● 添加背景音乐打开网页版网易云音乐,选择你准备添加的背景音乐,点击生成外链播放器,前提是要有版权,不然是无法生成外链播放器的,复制底下的HTML代码 然后将此代码放到你想要放的地方,比如放在博客的左侧,则打开 \themes\hexo-theme-spfk\layout_partial\left-col.ejs 文件,将复制的HTML代码粘贴进去,再进行适当的位置设置让播放器更美观,其中 auto=1 表示打开网页自动播放音乐,auto=0 表示关闭自动播放音乐 最后效果如下:这种网易云音乐外链的方式有很多局限性,因此推荐使用aplayer,GitHub地址为:https://github.com/MoePlayer/APlayer ,参考教程:《hexo上的aplayer应用》 ● 浏览器网页标题恶搞当用户访问你的博客时点击到了其他网页,我们可以恶搞一下网页标题,呼唤用户回来,首先在目录 \Hexo\themes\hexo-theme-spfk\source\js 下新建一个 FunnyTitle.js 文件,在里面填写如下代码: 123456789101112131415161718<!--浏览器搞笑标题--> var OriginTitle = document.title; var titleTime; document.addEventListener('visibilitychange', function () { if (document.hidden) { $('[rel="icon"]').attr('href', "/img/trhx2.png"); document.title = 'ヽ(●-`Д´-)ノ你丑你就走!'; clearTimeout(titleTime); } else { $('[rel="icon"]').attr('href', "/img/trhx2.png"); document.title = 'ヾ(Ő∀Ő3)ノ你帅就回来!' + OriginTitle; titleTime = setTimeout(function () { document.title = OriginTitle; }, 2000); } });1234567891011121314151617 然后在 \Hexo\themes\hexo-theme-spfk\layout\layout.ejs 文件中添加如下代码: 123<!--浏览器搞笑标题--><script type="text/javascript" src="\js\FunnyTitle.js"></script>12 再次部署博客后就可以看见标题搞笑的效果了: ● 背景添加动态线条效果在 \Hexo\themes\hexo-theme-spfk\layout\layout.ejs 文件中添加如下代码: 12345<!--动态线条背景--><script type="text/javascript"color="220,220,220" opacity='0.7' zIndex="-2" count="200" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>1234 其中: color:表示线条颜色,三个数字分别为(R,G,B),默认:(0,0,0) opacity:表示线条透明度(0~1),默认:0.5 count:表示线条的总数量,默认:150 zIndex:表示背景的z-index属性,css属性用于控制所在层的位置,默认:-1 最终实现效果: ● 添加人体时钟等有趣的挂件无意中发现了个有趣的人体时钟 HONE HONE CLOCK,作者是个日本人,点击此处访问作者博客,点击此处在作者原博客上查看动态样式,点击此处查看动态大图,如果你的博客上有合适的地方,加上一个人体时钟会很有趣的 实现代码: 123456<!--人体时钟背景透明--><script charset="Shift_JIS" src="http://chabudai.sakura.ne.jp/blogparts/honehoneclock/honehone_clock_tr.js"></script><!--人体时钟背景白--><script charset="Shift_JIS" src="http://chabudai.sakura.ne.jp/blogparts/honehoneclock/honehone_clock_wh.js"></script>12345 其他网页小挂件推荐: http://abowman.com/ 里面有很多有趣的小挂件,可以养养鱼、龟、狗、仓鼠等各式各样的虚拟宠物,能根据你的鼠标指针位置移动,直接复制代码就可以用 http://www.revolvermaps.com/ 它提供网站访客地理信息,可以以2D、3D等形式显示 http://www.amazingcounters.com/ 免费网站计数器,有非常多的样式供你选择,可以设置计数器初始数值,可以设置按访问量计数,也可以按独立访问者计数 https://www.seniverse.com/widget/get 心知天气提供基于Web的免费天气插件,可以为你的网站添加一项简洁美观的天气预报功能,并自动适配PC和手机上的浏览 ● 添加网站雪花飘落效果样式一和样式二分别如下: 实现方法:在 \Hexo\themes\hexo-theme-spfk\source\js 目录下新建一个 snow.js 文件,粘贴以下代码: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172/*样式一*/(function($){ $.fn.snow = function(options){ var $flake = $('<div id="snowbox" />').css({'position': 'absolute','z-index':'9999', 'top': '-50px'}).html('&#10052;'), documentHeight = $(document).height(), documentWidth = $(document).width(), defaults = { minSize : 10, maxSize : 20, newOn : 1000, flakeColor : "#AFDAEF" /* 此处可以定义雪花颜色,若要白色可以改为#FFFFFF */ }, options = $.extend({}, defaults, options); var interval= setInterval( function(){ var startPositionLeft = Math.random() * documentWidth - 100, startOpacity = 0.5 + Math.random(), sizeFlake = options.minSize + Math.random() * options.maxSize, endPositionTop = documentHeight - 200, endPositionLeft = startPositionLeft - 500 + Math.random() * 500, durationFall = documentHeight * 10 + Math.random() * 5000; $flake.clone().appendTo('body').css({ left: startPositionLeft, opacity: startOpacity, 'font-size': sizeFlake, color: options.flakeColor }).animate({ top: endPositionTop, left: endPositionLeft, opacity: 0.2 },durationFall,'linear',function(){ $(this).remove() }); }, options.newOn); };})(jQuery);$(function(){ $.fn.snow({ minSize: 5, /* 定义雪花最小尺寸 */ maxSize: 50,/* 定义雪花最大尺寸 */ newOn: 300 /* 定义密集程度,数字越小越密集 */ });});123456789101112131415161718192021222324252627282930313233343536373839404142/*样式二*//* 控制下雪 */function snowFall(snow) { /* 可配置属性 */ snow = snow || {}; this.maxFlake = snow.maxFlake || 200; /* 最多片数 */ this.flakeSize = snow.flakeSize || 10; /* 雪花形状 */ this.fallSpeed = snow.fallSpeed || 1; /* 坠落速度 */}/* 兼容写法 */requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { setTimeout(callback, 1000 / 60); };cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame;/* 开始下雪 */snowFall.prototype.start = function(){ /* 创建画布 */ snowCanvas.apply(this); /* 创建雪花形状 */ createFlakes.apply(this); /* 画雪 */ drawSnow.apply(this)}/* 创建画布 */function snowCanvas() { /* 添加Dom结点 */ var snowcanvas = document.createElement("canvas"); snowcanvas.id = "snowfall"; snowcanvas.width = window.innerWidth; snowcanvas.height = document.body.clientHeight; snowcanvas.setAttribute("style", "position:absolute; top: 0; left: 0; z-index: 1; pointer-events: none;"); document.getElementsByTagName("body")[0].appendChild(snowcanvas); this.canvas = snowcanvas; this.ctx = snowcanvas.getContext("2d"); /* 窗口大小改变的处理 */ window.onresize = function() { snowcanvas.width = window.innerWidth; /* snowcanvas.height = window.innerHeight */ }}/* 雪运动对象 */function flakeMove(canvasWidth, canvasHeight, flakeSize, fallSpeed) { this.x = Math.floor(Math.random() * canvasWidth); /* x坐标 */ this.y = Math.floor(Math.random() * canvasHeight); /* y坐标 */ this.size = Math.random() * flakeSize + 2; /* 形状 */ this.maxSize = flakeSize; /* 最大形状 */ this.speed = Math.random() * 1 + fallSpeed; /* 坠落速度 */ this.fallSpeed = fallSpeed; /* 坠落速度 */ this.velY = this.speed; /* Y方向速度 */ this.velX = 0; /* X方向速度 */ this.stepSize = Math.random() / 30; /* 步长 */ this.step = 0 /* 步数 */}flakeMove.prototype.update = function() { var x = this.x, y = this.y; /* 左右摆动(余弦) */ this.velX *= 0.98; if (this.velY <= this.speed) { this.velY = this.speed } this.velX += Math.cos(this.step += .05) * this.stepSize; this.y += this.velY; this.x += this.velX; /* 飞出边界的处理 */ if (this.x >= canvas.width || this.x <= 0 || this.y >= canvas.height || this.y <= 0) { this.reset(canvas.width, canvas.height) }};/* 飞出边界-放置最顶端继续坠落 */flakeMove.prototype.reset = function(width, height) { this.x = Math.floor(Math.random() * width); this.y = 0; this.size = Math.random() * this.maxSize + 2; this.speed = Math.random() * 1 + this.fallSpeed; this.velY = this.speed; this.velX = 0;};// 渲染雪花-随机形状(此处可修改雪花颜色!!!)flakeMove.prototype.render = function(ctx) { var snowFlake = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size); snowFlake.addColorStop(0, "rgba(255, 255, 255, 0.9)"); /* 此处是雪花颜色,默认是白色 */ snowFlake.addColorStop(.5, "rgba(255, 255, 255, 0.5)"); /* 若要改为其他颜色,请自行查 */ snowFlake.addColorStop(1, "rgba(255, 255, 255, 0)"); /* 找16进制的RGB 颜色代码。 */ ctx.save(); ctx.fillStyle = snowFlake; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); ctx.restore();};/* 创建雪花-定义形状 */function createFlakes() { var maxFlake = this.maxFlake, flakes = this.flakes = [], canvas = this.canvas; for (var i = 0; i < maxFlake; i++) { flakes.push(new flakeMove(canvas.width, canvas.height, this.flakeSize, this.fallSpeed)) }}/* 画雪 */function drawSnow() { var maxFlake = this.maxFlake, flakes = this.flakes; ctx = this.ctx, canvas = this.canvas, that = this; /* 清空雪花 */ ctx.clearRect(0, 0, canvas.width, canvas.height); for (var e = 0; e < maxFlake; e++) { flakes[e].update(); flakes[e].render(ctx); } /* 一帧一帧的画 */ this.loop = requestAnimationFrame(function() { drawSnow.apply(that); });}/* 调用及控制方法 */var snow = new snowFall({maxFlake:60});snow.start();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 然后在 \Hexo\themes\hexo-theme-spfk\layout\layout.ejs 文件里引用即可: 123<!-- 雪花特效 --><script type="text/javascript" src="\js\snow.js"></script>12 如果没效果,请确认网页是否已载入JQurey,如果没有请在下雪代码之前引入JQ即可: 123<script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.js"></script><script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>12 原文链接:《分享两种圣诞节雪花特效JS代码(网站下雪效果)》 ● 添加背景动态彩带效果样式一是鼠标点击后彩带自动更换样式,样式二是飘动的彩带: 实现方法:在 \themes\material-x\layout\layout.ejs 文件的body前面添加如下代码: 123456<!-- 样式一(鼠标点击更换样式) --><script src="https://g.joyinshare.com/hc/ribbon.min.js" type="text/javascript"></script>12<!-- 样式二(飘动的彩带) --><script src="https://g.joyinshare.com/hc/piao.js" type="text/javascript"></script>12 ● 添加背景代码雨特效新建 DigitalRain.js,写入以下代码: 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758window.onload = function(){ //获取画布对象 var canvas = document.getElementById("canvas"); //获取画布的上下文 var context =canvas.getContext("2d"); var s = window.screen; var W = canvas.width = s.width; var H = canvas.height; //获取浏览器屏幕的宽度和高度 //var W = window.innerWidth; //var H = window.innerHeight; //设置canvas的宽度和高度 canvas.width = W; canvas.height = H; //每个文字的字体大小 var fontSize = 12; //计算列 var colunms = Math.floor(W /fontSize); //记录每列文字的y轴坐标 var drops = []; //给每一个文字初始化一个起始点的位置 for(var i=0;i<colunms;i++){ drops.push(0); } //运动的文字 var str ="WELCOME TO WWW.ITRHX.COM"; //4:fillText(str,x,y);原理就是去更改y的坐标位置 //绘画的函数 function draw(){ context.fillStyle = "rgba(238,238,238,.08)";//遮盖层 context.fillRect(0,0,W,H); //给字体设置样式 context.font = "600 "+fontSize+"px Georgia"; //给字体添加颜色 context.fillStyle = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444", "#CC0000"][parseInt(Math.random() * 10)];//randColor();可以rgb,hsl, 标准色,十六进制颜色 //写入画布中 for(var i=0;i<colunms;i++){ var index = Math.floor(Math.random() * str.length); var x = i*fontSize; var y = drops[i] *fontSize; context.fillText(str[index],x,y); //如果要改变时间,肯定就是改变每次他的起点 if(y >= canvas.height && Math.random() > 0.99){ drops[i] = 0; } drops[i]++; } }; function randColor(){//随机颜色 var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return "rgb("+r+","+g+","+b+")"; } draw(); setInterval(draw,35);};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 在主题文件的相关css文件中(以 Material X 1.2.1 主题为例,在\themes\material-x-1.2.1\source\less_main.less 文件末尾)添加以下代码: 1234567891011canvas { position: fixed; right: 0px; bottom: 0px; min-width: 100%; min-height: 100%; height: auto; width: auto; z-index: -1;}12345678910 然后在主题的 layout.ejs 文件中引入即可: 1234 <!-- 数字雨 --> <canvas id="canvas" width="1440" height="900" ></canvas> <script type="text/javascript" src="/js/DigitalRain.js"></script>123 最终效果:代码来源:http://www.lxl8800.cn/Main/Resource 未完待续…]]></content>
<categories>
<category>hexo</category>
</categories>
<tags>
<tag>hexo</tag>
</tags>
</entry>
<entry>
<title><![CDATA[hexo博客的背景设置]]></title>
<url>%2F2019%2F08%2F24%2Fhexo%E5%8D%9A%E5%AE%A2%E7%9A%84%E8%83%8C%E6%99%AF%E8%AE%BE%E7%BD%AE%2F</url>
<content type="text"><![CDATA[hexo博客的背景设置主要有以下30种: 在右上角或者左上角实现fork me on github 添加RSS 添加动态背景 实现点击出现桃心效果 修改文章内链接文本样式 修改文章底部的那个带#号的标签 在每篇文章末尾统一添加“本文结束”标记 修改作者头像并旋转 博文压缩 修改“代码块自定义样式 侧边栏社交小图标设置 主页文章添加阴影效果 在网站底部加上访问量 添加热度 网站底部字数统计 添加 README.md 文件 设置网站的图标Favicon 实现统计功能 添加顶部加载条 在文章底部增加版权信息 添加网易云跟帖(跟帖关闭,已失效,改为来必力) 隐藏网页底部powered By Hexo / 强力驱动 修改网页底部的桃心 文章加密访问 添加jiathis分享 博文置顶 修改字体大小 修改打赏字体不闪动 侧边栏推荐阅读 自定义鼠标样式 1. 在右上角或者左上角实现fork me on github实现效果图 具体实现方法 点击这里挑选自己喜欢的样式,并复制代码。 例如,我是复制如下代码: 然后粘贴刚才复制的代码到themes/next/layout/_layout.swig文件中(放在<div class="headband"></div>的下面),并把href改为你的github地址 2.添加RSS实现效果图 具体实现方法 切换到你的blog(我是取名blog,具体的看你们的取名是什么)的路径,例如我是在/Users/chenzekun/Code/Hexo/blog这个路径上,也就是在你的根目录下 然后安装 Hexo 插件:(这个插件会放在node_modules这个文件夹里) 1$ npm install --save hexo-generator-feed 1 1 接下来打开画红线的文件,如下图: 在里面的末尾添加:(请注意在冒号后面要加一个空格,不然会发生错误!) 123456789# Extensions## Plugins: http://hexo.io/plugins/plugins: hexo-generate-feed 然后打开next主题文件夹里面的_config.yml,在里面配置为如下样子:(就是在rss:的后面加上/atom.xml,注意在冒号后面要加一个空格) 12345678910111213# Set rss to false to disable feed link.# Leave rss as empty to use site's feed link.# Set rss to specific value if you have burned your feed already.rss: /atom.xml 配置完之后运行: 1$ hexo g 重新生成一次,你会在./public 文件夹中看到 atom.xml 文件。然后启动服务器查看是否有效,之后再部署到 Github 中。 3. 添加动态背景实现效果图 具体实现方法 这个我之前有一篇文章有讲过了,详情点击我的博客 4. 实现点击出现桃心效果实现效果图 具体实现方法 在网址输入如下 1http://7u2ss1.com1.z0.glb.clouddn.com/love.js 然后将里面的代码copy一下,新建love.js文件并且将代码复制进去,然后保存。将love.js文件放到路径/themes/next/source/js/src里面,然后打开\themes\next\layout\_layout.swig文件,在末尾(在前面引用会出现找不到的bug)添加以下代码: 12345<!-- 页面点击小红心 --><script type="text/javascript" src="/js/src/love.js"></script> 5. 修改文章内链接文本样式实现效果图 具体实现方法 修改文件 themes\next\source\css\_common\components\post\post.styl,在末尾添加如下css样式,: 1234567891011121314151617181920212223242526272829303132333435363738394041// 文章内链接文本样式.post-body p a{ color: #0593d3; border-bottom: none; border-bottom: 1px solid #0593d3; &:hover { color: #fc6423; border-bottom: none; border-bottom: 1px solid #fc6423; }} 其中选择.post-body 是为了不影响标题,选择 p 是为了不影响首页“阅读全文”的显示样式,颜色可以自己定义。 6. 修改文章底部的那个带#号的标签实现效果图 具体实现方法 修改模板/themes/next/layout/_macro/post.swig,搜索 rel="tag">#,将 # 换成<i class="fa fa-tag"></i> 7. 在每篇文章末尾统一添加“本文结束”标记实现效果图 具体实现方法 在路径 \themes\next\layout\_macro 中新建 passage-end-tag.swig 文件,并添加以下内容: 1234567891011121314151617<div> {% if not is_index %} <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div> {% endif %}</div> 接着打开\themes\next\layout\_macro\post.swig文件,在post-body 之后, post-footer 之前添加如下画红色部分代码(post-footer之前两个DIV): 代码如下: 1234567891011121314151617<div> {% if not is_index %} {% include 'passage-end-tag.swig' %} {% endif %}</div> 然后打开主题配置文件(_config.yml),在末尾添加: 123456789# 文章末尾添加“本文结束”标记passage_end_tag: enabled: true 完成以上设置之后,在每篇文章之后都会添加如上效果图的样子。 8. 修改作者头像并旋转实现效果图 具体实现方法 打开\themes\next\source\css\_common\components\sidebar\sidebar-author.styl,在里面添加如下代码: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237.site-author-image { display: block; margin: 0 auto; padding: $site-author-image-padding; max-width: $site-author-image-width; height: $site-author-image-height; border: $site-author-image-border-width solid $site-author-image-border-color; /* 头像圆形 */ border-radius: 80px; -webkit-border-radius: 80px; -moz-border-radius: 80px; box-shadow: inset 0 -1px 0 #333sf; /* 设置循环动画 [animation: (play)动画名称 (2s)动画播放时长单位秒或微秒 (ase-out)动画播放的速度曲线为以低速结束 (1s)等待1秒然后开始动画 (1)动画播放次数(infinite为循环播放) ]*/ /* 鼠标经过头像旋转360度 */ -webkit-transition: -webkit-transform 1.0s ease-out; -moz-transition: -moz-transform 1.0s ease-out; transition: transform 1.0s ease-out;} img:hover { /* 鼠标经过停止头像旋转 -webkit-animation-play-state:paused; animation-play-state:paused;*/ /* 鼠标经过头像旋转360度 */ -webkit-transform: rotateZ(360deg); -moz-transform: rotateZ(360deg); transform: rotateZ(360deg);} /* Z 轴旋转动画 */@-webkit-keyframes play { 0% { -webkit-transform: rotateZ(0deg); } 100% { -webkit-transform: rotateZ(-360deg); }}@-moz-keyframes play { 0% { -moz-transform: rotateZ(0deg); } 100% { -moz-transform: rotateZ(-360deg); }}@keyframes play { 0% { transform: rotateZ(0deg); } 100% { transform: rotateZ(-360deg); }} 9. 博文压缩在站点的根目录下执行以下命令: 12345$ npm install gulp -g$ npm install gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp --save 在如下图所示,新建 gulpfile.js ,并填入以下内容: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129var gulp = require('gulp');var minifycss = require('gulp-minify-css');var uglify = require('gulp-uglify');var htmlmin = require('gulp-htmlmin');var htmlclean = require('gulp-htmlclean');// 压缩 public 目录 cssgulp.task('minify-css', function() { return gulp.src('./public/**/*.css') .pipe(minifycss()) .pipe(gulp.dest('./public'));});// 压缩 public 目录 htmlgulp.task('minify-html', function() { return gulp.src('./public/**/*.html') .pipe(htmlclean()) .pipe(htmlmin({ removeComments: true, minifyJS: true, minifyCSS: true, minifyURLs: true, })) .pipe(gulp.dest('./public'))});// 压缩 public/js 目录 jsgulp.task('minify-js', function() { return gulp.src('./public/**/*.js') .pipe(uglify()) .pipe(gulp.dest('./public'));});// 执行 gulp 命令时执行的任务gulp.task('default', [ 'minify-html','minify-css','minify-js']); 生成博文是执行 hexo g && gulp 就会根据 gulpfile.js 中的配置,对 public 目录中的静态资源文件进行压缩。 10. 修改“代码块自定义样式实现效果图 具体实现方法 打开\themes\next\source\css\_custom\custom.styl,向里面加入:(颜色可以自己定义) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657// Custom styles.code { color: #ff7600; background: #fbf7f8; margin: 2px;}// 大代码块的自定义样式.highlight, pre { margin: 5px 0; padding: 5px; border-radius: 3px;}.highlight, code, pre { border: 1px solid #d6d6d6;} 11. 侧边栏社交小图标设置实现效果图 具体实现方法 打开主题配置文件(_config.yml),搜索social_icons:,在图标库找自己喜欢的小图标,并将名字复制在如下位置,保存即可 12. 主页文章添加阴影效果实现效果图 具体实现方法 打开\themes\next\source\css\_custom\custom.styl,向里面加入: 1234567891011121314151617181920212223242526272829// 主页文章添加阴影效果 .post { margin-top: 60px; margin-bottom: 60px; padding: 25px; -webkit-box-shadow: 0 0 5px rgba(202, 203, 203, .5); -moz-box-shadow: 0 0 5px rgba(202, 203, 204, .5); } 13. 在网站底部加上访问量实现效果图 具体实现方法 打开\themes\next\layout_partials\footer.swig文件,在copyright前加上画红线这句话: 代码如下: 1<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script> 然后再合适的位置添加显示统计的代码,如图: 代码如下: 1234567891011121314151617<div class="powered-by"><i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv"> 本站访客数:<span id="busuanzi_value_site_uv"></span></span></div> 在这里有两中不同计算方式的统计代码: \1. pv的方式,单个用户连续点击n篇文章,记录n次访问量 123456789<span id="busuanzi_container_site_pv"> 本站总访问量<span id="busuanzi_value_site_pv"></span>次</span> uv的方式,单个用户连续点击n篇文章,只记录1次访客数 123456789<span id="busuanzi_container_site_uv"> 本站总访问量<span id="busuanzi_value_site_uv"></span>次</span> 添加之后再执行hexo d -g,然后再刷新页面就能看到效果 14. 添加热度实现效果图 具体实现方法 next主题集成leanCloud,打开/themes/next/layout/_macro/post.swig,在画红线的区域添加℃: 然后打开,/themes/next/languages/zh-Hans.yml,将画红框的改为热度就可以了 15. 网站底部字数统计实现效果图 具体方法实现 切换到根目录下,然后运行如下代码 1$ npm install hexo-wordcount --save 1 1 然后在/themes/next/layout/_partials/footer.swig文件尾部加上: 12345678910111213<div class="theme-info"> <div class="powered-by"></div> <span class="post-count">博客全站共{{ totalcount(site) }}字</span></div> 16. 添加 README.md 文件每个项目下一般都有一个 README.md 文件,但是使用 hexo 部署到仓库后,项目下是没有 README.md 文件的。 在 Hexo 目录下的 source 根目录下添加一个 README.md 文件,修改站点配置文件 _config.yml,将 skip_render 参数的值设置为 1skip_render: README.md 保存退出即可。再次使用 hexo d 命令部署博客的时候就不会在渲染 README.md 这个文件了。 17. 设置网站的图标Favicon实现效果图 具体方法实现 在EasyIcon中找一张(32*32)的ico图标,或者去别的网站下载或者制作,并将图标名称改为favicon.ico,然后把图标放在/themes/next/source/images里,并且修改主题配置文件: 12345# Put your favicon.ico into `hexo-site/source/` directory.favicon: /favicon.ico 18. 实现统计功能实现效果图 具体实现方法 在根目录下安装 hexo-wordcount,运行: 1$ npm install hexo-wordcount --save 然后在主题的配置文件中,配置如下: 123456789101112131415161718192021# Post wordcount display settings# Dependencies: https://github.com/willin/hexo-wordcountpost_wordcount: item_text: true wordcount: true min2read: true 19. 添加顶部加载条实现效果图 具体实现方法 打开/themes/next/layout/_partials/head.swig文件,添加红框上的代码 代码如下: 12345<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script><link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet"> 1 2 1 2 但是,默认的是粉色的,要改变颜色可以在/themes/next/layout/_partials/head.swig文件中添加如下代码(接在刚才link的后面) 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849<style> .pace .pace-progress { background: #1E92FB; /*进度条颜色*/ height: 3px; } .pace .pace-progress-inner { box-shadow: 0 0 10px #1E92FB, 0 0 5px #1E92FB; /*阴影颜色*/ } .pace .pace-activity { border-top-color: #1E92FB; /*上边框颜色*/ border-left-color: #1E92FB; /*左边框颜色*/ }</style> 目前,博主的增加顶部加载条的pull request 已被Merge��===>详情 现在升级最新版的next主题,升级后只需修改主题配置文件(_config.yml)将pace: false改为pace: true就行了,你还可以换不同样式的加载条,如下图: 20. 在文章底部增加版权信息实现效果图 在目录 next/layout/_macro/下添加 my-copyright.swig: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{% if page.copyright %}<div class="my_post_copyright"> <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script> <!-- JS库 sweetalert 可修改路径 --> <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script> <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script> <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css"> <p><span>本文标题:</span><a href="{{ url_for(page.path) }}">{{ page.title }}</a></p> <p><span>文章作者:</span><a href="/" title="访问 {{ theme.author }} 的个人博客">{{ theme.author }}</a></p> <p><span>发布时间:</span>{{ page.date.format("YYYY年MM月DD日 - HH:MM") }}</p> <p><span>最后更新:</span>{{ page.updated.format("YYYY年MM月DD日 - HH:MM") }}</p> <p><span>原始链接:</span><a href="{{ url_for(page.path) }}" title="{{ page.title }}">{{ page.permalink }}</a> <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="{{ page.permalink }}" aria-label="复制成功!"></i></span> </p> <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p> </div><script> var clipboard = new Clipboard('.fa-clipboard'); clipboard.on('success', $(function(){ $(".fa-clipboard").click(function(){ swal({ title: "", text: '复制成功', html: false, timer: 500, showConfirmButton: false }); }); })); </script>{% endif %} 在目录next/source/css/_common/components/post/下添加my-post-copyright.styl: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177.my_post_copyright { width: 85%; max-width: 45em; margin: 2.8em auto 0; padding: 0.5em 1.0em; border: 1px solid #d3d3d3; font-size: 0.93rem; line-height: 1.6em; word-break: break-all; background: rgba(255,255,255,0.4);}.my_post_copyright p{margin:0;}.my_post_copyright span { display: inline-block; width: 5.2em; color: #b5b5b5; font-weight: bold;}.my_post_copyright .raw { margin-left: 1em; width: 5em;}.my_post_copyright a { color: #808080; border-bottom:0;}.my_post_copyright a:hover { color: #a3d2a3; text-decoration: underline;}.my_post_copyright:hover .fa-clipboard { color: #000;}.my_post_copyright .post-url:hover { font-weight: normal;}.my_post_copyright .copy-path { margin-left: 1em; width: 1em; +mobile(){display:none;}}.my_post_copyright .copy-path:hover { color: #808080; cursor: pointer;} 修改next/layout/_macro/post.swig,在代码 1234567891011121314151617<div> {% if not is_index %} {% include 'wechat-subscriber.swig' %} {% endif %}</div> 之前添加增加如下代码: 1234567891011121314151617<div> {% if not is_index %} {% include 'my-copyright.swig' %} {% endif %}</div> 如下: 修改next/source/css/_common/components/post/post.styl文件,在最后一行增加代码: 1@import "my-post-copyright" 保存重新生成即可。 如果要在该博文下面增加版权信息的显示,需要在 Markdown 中增加copyright: true的设置,类似: 小技巧:如果你觉得每次都要输入copyright: true很麻烦的话,那么在/scaffolds/post.md文件中添加: 这样每次hexo new "你的内容"之后,生成的md文件会自动把copyright:加到里面去 (注意:如果解析出来之后,你的原始链接有问题:如:http://yoursite.com/前端小项目:使用canvas绘画哆啦A梦.html,那么在根目录下_config.yml中写成类似这样:)就行了。 21. 添加网易云跟帖(跟帖关闭,已失效,改为来必力)实现效果图 具体方法实现 有两种实现方法: ①更新next主题,因为最新版本的主题已经支持这种评论。直接在主题配置文件_config.yml 文件中添加如下配置: 1gentie_productKey: #your-gentie-product-key ②如果你不想更新的话,那么按下面步骤进行: 首先,还是在主题配置文件_config.yml 文件中添加如下配置: 1gentie_productKey: #your-gentie-product-key 你的productKey就是下面画红线部分 然后在在layout/_scripts/third-party/comments/ 目录中添加 gentie.swig,文件内容如下: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{% if not (theme.duoshuo and theme.duoshuo.shortname) and not theme.duoshuo_shortname and not theme.disqus_shortname and not theme.hypercomments_id %} {% if theme.gentie_productKey %} {% set gentie_productKey = theme.gentie_productKey %} <script> var cloudTieConfig = { url: document.location.href, sourceId: "", productKey: "{{gentie_productKey}}", target: "cloud-tie-wrapper" }; </script> <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script> {% endif %}{% endif %} 然后在layout/_scripts/third-party/comments.swig文件中追加: 1{% include './comments/gentie.swig' %} 1 1 最后,在 layout/_partials/comments.swig 文件中条件最后追加网易云跟帖插件引用的判断逻辑: 123456789{% elseif theme.gentie_productKey %} <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"> </div> 具体位置如下: 可能你hexo s时可能看不到,直接hexo d就可以看到了 近日,我朋友发来消息,说网易云跟帖要关了,我网上查了一下,果然如此 ��都是泪,上次用了多说,结果多说关了,接着是网易云跟帖��,这次直接用国外的来必力,应该不会这么容易关吧�� 方法其实还是跟上面差不多的 首先在 _config.yml 文件中添加如下配置: 123456789# Support for LiveRe comments system.# You can get your uid from https://livere.com/insight/myCode (General web site)livere_uid: your uid 其中,livere_uid就是画红线的部分 然后在 layout/_scripts/third-party/comments/ 目录中添加 livere.swig,文件内容如下: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{% if not (theme.duoshuo and theme.duoshuo.shortname) and not theme.duoshuo_shortname and not theme.disqus_shortname and not theme.hypercomments_id and not theme.gentie_productKey %} {% if theme.livere_uid %} <script type="text/javascript"> (function(d, s) { var j, e = d.getElementsByTagName(s)[0]; if (typeof LivereTower === 'function') { return; } j = d.createElement(s); j.src = 'https://cdn-city.livere.com/js/embed.dist.js'; j.async = true; e.parentNode.insertBefore(j, e); })(document, 'script'); </script> {% endif %}{% endif %} 然后在 layout/_scripts/third-party/comments.swig文件中追加: 1{% include './comments/livere.swig' %} 最后,在 layout/_partials/comments.swig 文件中条件最后追加 LiveRe 插件是否引用的判断逻辑: 123456789{% elseif theme.livere_uid %} <div id="lv-container" data-id="city" data-uid="{{ theme.livere_uid }}"></div>{% endif %} 完 22. 隐藏网页底部powered By Hexo / 强力驱动打开themes/next/layout/_partials/footer.swig,使用””隐藏之间的代码即可,或者直接删除。位置如图: 23. 修改网页底部的桃心还是打开themes/next/layout/_partials/footer.swig,找到:,然后还是在图标库中找到你自己喜欢的图标,然后修改画红线的部分就可以了。 24. 文章加密访问实现效果图 具体实现方法 打开themes->next->layout->_partials->head.swig文件,在以下位置插入这样一段代码: 代码如下: 12345678910111213141516171819202122232425262728293031323334353637<script> (function(){ if('{{ page.password }}'){ if (prompt('请输入文章密码') !== '{{ page.password }}'){ alert('密码错误!'); history.back(); } } })();</script> 然后在文章上写成类似这样: 25. 添加jiathis分享在主题配置文件中,jiathis为true,就行了,如下图 默认是这样子的: 如果你想自定义话,打开themes/next/layout/_partials/share/jiathis.swig修改画红线部分就可以了 26. 博文置顶修改 hero-generator-index 插件,把文件:node_modules/hexo-generator-index/lib/generator.js 内的代码替换为: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109'use strict';var pagination = require('hexo-pagination');module.exports = function(locals){ var config = this.config; var posts = locals.posts; posts.data = posts.data.sort(function(a, b) { if(a.top && b.top) { // 两篇文章top都有定义 if(a.top == b.top) return b.date - a.date; // 若top值一样则按照文章日期降序排 else return b.top - a.top; // 否则按照top值降序排 } else if(a.top && !b.top) { // 以下是只有一篇文章top有定义,那么将有top的排在前面(这里用异或操作居然不行233) return -1; } else if(!a.top && b.top) { return 1; } else return b.date - a.date; // 都没定义按照文章日期降序排 }); var paginationDir = config.pagination_dir || 'page'; return pagination('', posts, { perPage: config.index_generator.per_page, layout: ['index', 'archive'], format: paginationDir + '/%d/', data: { __index: true } });}; 在文章中添加 top 值,数值越大文章越靠前,如 1234567891011121314151617181920212223242526272829---title: 解决Charles乱码问题date: 2017-05-22 22:45:48tags: 技巧categories: 技巧copyright: truetop: 100--- 27. 修改字体大小打开\themes\next\source\css\ _variables\base.styl文件,将$font-size-base改成16px,如下所示: 1$font-size-base =16px 28. 修改打赏字体不闪动修改文件next/source/css/_common/components/post/post-reward.styl,然后注释其中的函数wechat:hover和alipay:hover,如下: 123456789101112131415161718192021222324252627282930313233343536373839404142434445/* 注释文字闪动函数 #wechat:hover p{ animation: roll 0.1s infinite linear; -webkit-animation: roll 0.1s infinite linear; -moz-animation: roll 0.1s infinite linear;} #alipay:hover p{ animation: roll 0.1s infinite linear; -webkit-animation: roll 0.1s infinite linear; -moz-animation: roll 0.1s infinite linear;}*/ 29. 侧边栏推荐阅读今天有位网友问推荐阅读是怎么弄,其实挺简单的,打开主题配置文件修改成这样就行了(links里面写你想要的链接): 1234567891011121314151617181920212223242526272829303132333435363738394041# Blogrollslinks_title: 推荐阅读#links_layout: blocklinks_layout: inlinelinks: 优设: http://www.uisdc.com/ 张鑫旭: http://www.zhangxinxu.com/ Web前端导航: http://www.alloyteam.com/nav/ 前端书籍资料: http://www.36zhen.com/t?id=3448 百度前端技术学院: http://ife.baidu.com/ google前端开发基础: http://wf.uisdc.com/cn/ 30. 自定义鼠标样式打开themes/next/source/css/_custom/custom.styl,在里面写下如下代码 12345678910111213141516171819202122232425// 鼠标样式 * { cursor: url("http://om8u46rmb.bkt.clouddn.com/sword2.ico"),auto!important } :active { cursor: url("http://om8u46rmb.bkt.clouddn.com/sword1.ico"),auto!important } 其中 url 里面必须是 ico 图片,ico 图片可以上传到网上(我是使用七牛云图床),然后获取外链,复制到 url 里就行了]]></content>
<categories>
<category>hexo</category>
</categories>
<tags>
<tag>hexo博客的背景设置</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Redis入门,读这一篇就够了]]></title>
<url>%2F2019%2F08%2F23%2FRedis%E5%85%A5%E9%97%A8%EF%BC%8C%E8%AF%BB%E8%BF%99%E4%B8%80%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86%2F</url>
<content type="text">< 2. [Redis中文网](http://www.redis.net.cn/) 3. 解压直接可以使用: redis.windows.conf:配置文件 redis-cli.exe:redis的客户端 redis-server.exe:redis服务器端三. 命令操作1. redis的数据结构: redis存储的是:key,value格式的数据,其中key都是字符串,value有5种不同的数据结构 value的数据结构: 字符串类型 string 哈希类型 hash : map格式 列表类型 list : linkedlist格式。支持重复元素 集合类型 set : 不允许重复元素 有序集合类型 sortedset:不允许重复元素,且元素有顺序 2. 字符串类型 string1. 存储: set key value 127.0.0.1:6379> set username zhangsan OK 2. 获取: get key 127.0.0.1:6379> get username "zhangsan" 3. 删除: del key 127.0.0.1:6379> del age (integer) 13. 哈希类型 hash**1. 存储**: hset key field value 127.0.0.1:6379> hset myhash username lisi (integer) 1 127.0.0.1:6379> hset myhash password 123 (integer) 1 **2. 获取**: hget key field: 获取指定的field对应的值 127.0.0.1:6379> hget myhash username "lisi" hgetall key:获取所有的field和value 127.0.0.1:6379> hgetall myhash 1) "username" 2) "lisi" 3) "password" 4) "123" **3. 删除**: hdel key field 127.0.0.1:6379> hdel myhash username (integer) 14. 列表类型 list:可以添加一个元素到列表的头部(左边)或者尾部(右边) 添加: 1. lpush key value: 将元素加入列表左表 2. rpush key value:将元素加入列表右边 127.0.0.1:6379> lpush myList a (integer) 1 127.0.0.1:6379> lpush myList b (integer) 2 127.0.0.1:6379> rpush myList c (integer) 3 2. 获取: lrange key start end :范围获取 127.0.0.1:6379> lrange myList 0 -1 1) "b" 2) "a" 3) "c" 3. 删除: lpop key: 删除列表最左边的元素,并将元素返回 rpop key: 删除列表最右边的元素,并将元素返回 5. 集合类型 set : 不允许重复元素**1. 存储**:sadd key value 127.0.0.1:6379> sadd myset a (integer) 1 127.0.0.1:6379> sadd myset a (integer) 0 **2. 获取**:smembers key:获取set集合中所有元素 127.0.0.1:6379> smembers myset 1) "a" **3. 删除**:srem key value:删除set集合中的某个元素 127.0.0.1:6379> srem myset a (integer) 16. 有序集合类型 sortedset: 不允许重复元素,且元素有顺序.每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。 1. 存储:zadd key score value 127.0.0.1:6379> zadd mysort 60 zhangsan (integer) 1 127.0.0.1:6379> zadd mysort 50 lisi (integer) 1 127.0.0.1:6379> zadd mysort 80 wangwu (integer) 1 2. 获取:zrange key start end [withscores] 127.0.0.1:6379> zrange mysort 0 -1 1) “lisi” 2) “zhangsan” 3) “wangwu” 127.0.0.1:6379> zrange mysort 0 -1 withscores 1) “zhangsan” 2) “60” 3) “wangwu” 4) “80” 5) “lisi” 6) “500” 3. 删除:zrem key value 127.0.0.1:6379> zrem mysort lisi (integer) 1 7. 通用命令1. keys * : 查询所有的键 2. type key : 获取键对应的value的类型 3. del key:删除指定的key value四. 持久化1. redis是一个内存数据库 当redis服务器重启,获取电脑重启,数据会丢失,我们可以将redis内存中的数据持久化保存到硬盘的文件中。 2. redis持久化机制:1. RDB:默认方式,不需要进行配置,默认就使用这种机制在一定的间隔时间中,检测key的变化情况,然后持久化数据 1. 编辑redis.windwos.conf文件 after 900 sec (15 min) if at least 1 key changed save 900 1 after 300 sec (5 min) if at least 10 keys changed save 300 10 after 60 sec if at least 10000 keys changed save 60 10000 2. 重新启动redis服务器,并指定配置文件名称 D:\JavaWeb2018\day23_redis\资料\redis\windows-64\redis-2.8.9>redis-server.exe redis.windows.conf 2. AOF:日志记录的方式,可以记录每一条命令的操作。可以每一次命令操作后,持久化数据1. 编辑redis.windwos.conf文件 appendonly no(关闭aof) --> appendonly yes (开启aof) \# appendfsync always : 每一次操作都进行持久化 appendfsync everysec : 每隔一秒进行一次持久化 \# appendfsync no : 不进行持久化五. Java客户端 Jedis Jedis: 一款java操作redis数据库的工具. 使用步骤: 1. 下载jedis的jar包 2. 使用 //1. 获取连接 Jedis jedis = new Jedis(“localhost”,6379); //2. 操作 jedis.set(“username”,”zhangsan”); //3. 关闭连接 jedis.close(); Jedis操作各种redis中的数据结构 1) 字符串类型 string set get //1. 获取连接 Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口 //2. 操作 //存储 jedis.set(“username”,”zhangsan”); //获取 String username = jedis.get(“username”); System.out.println(username); //可以使用setex()方法存储可以指定过期时间的 key value jedis.setex(“activecode”,20,”hehe”);//将activecode:hehe键值对存入redis,并且20秒后自动删除该键值对 //3. 关闭连接 jedis.close(); 2) 哈希类型 hash : map格式 hset hget hgetAll //1. 获取连接 Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口 //2. 操作 // 存储hash jedis.hset(“user”,”name”,”lisi”); jedis.hset(“user”,”age”,”23”); jedis.hset(“user”,”gender”,”female”); // 获取hash String name = jedis.hget(“user”, “name”); System.out.println(name); // 获取hash的所有map中的数据 Map<String, String> user = jedis.hgetAll(“user”); // keyset Set keySet = user.keySet(); for (String key : keySet) { //获取value String value = user.get(key); System.out.println(key + “:” + value); } //3. 关闭连接 jedis.close(); 3) 列表类型 list : linkedlist格式。支持重复元素 lpush / rpush lpop / rpop lrange start end : 范围获取 //1. 获取连接 Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口 //2. 操作 // list 存储 jedis.lpush("mylist","a","b","c");//从左边存 jedis.rpush("mylist","a","b","c");//从右边存 // list 范围获取 List<String> mylist = jedis.lrange("mylist", 0, -1); System.out.println(mylist); // list 弹出 String element1 = jedis.lpop("mylist");//c System.out.println(element1); String element2 = jedis.rpop("mylist");//c System.out.println(element2); // list 范围获取 List<String> mylist2 = jedis.lrange("mylist", 0, -1); System.out.println(mylist2); //3. 关闭连接 jedis.close(); 4) 集合类型 set : 不允许重复元素 sadd smembers:获取所有元素 //1. 获取连接 Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口 //2. 操作 // set 存储 jedis.sadd(“myset”,”java”,”php”,”c++”); // set 获取 Set myset = jedis.smembers(“myset”); System.out.println(myset); //3. 关闭连接 jedis.close(); 5) 有序集合类型 sortedset:不允许重复元素,且元素有顺序 zadd zrange //1. 获取连接 Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口 //2. 操作 // sortedset 存储 jedis.zadd(“mysortedset”,3,”亚瑟”); jedis.zadd(“mysortedset”,30,”后裔”); jedis.zadd(“mysortedset”,55,”孙悟空”); // sortedset 获取 Set mysortedset = jedis.zrange(“mysortedset”, 0, -1); System.out.println(mysortedset); //3. 关闭连接 jedis.close(); jedis连接池: JedisPool * 使用: 1. 创建JedisPool连接池对象 2. 调用方法 getResource()方法获取Jedis连接 //0.创建一个配置对象 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(50); config.setMaxIdle(10); //1.创建Jedis连接池对象 JedisPool jedisPool = new JedisPool(config,"localhost",6379); //2.获取连接 Jedis jedis = jedisPool.getResource(); //3. 使用 jedis.set("hehe","heihei"); //4. 关闭 归还到连接池中 jedis.close(); * 连接池工具类 public class JedisPoolUtils { private static JedisPool jedisPool; static{ //读取配置文件 InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream(“jedis.properties”); //创建Properties对象 Properties pro = new Properties(); //关联文件 try { pro.load(is); } catch (IOException e) { e.printStackTrace(); } //获取数据,设置到JedisPoolConfig中 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(pro.getProperty(“maxTotal”))); config.setMaxIdle(Integer.parseInt(pro.getProperty(“maxIdle”))); //初始化JedisPool jedisPool = new JedisPool(config,pro.getProperty(“host”),Integer.parseInt(pro.getProperty(“port”))); } /* \ 获取连接方法 */ public static Jedis getJedis(){ return jedisPool.getResource(); } } 六. 案例: 案例需求: 1. 提供index.html页面,页面中有一个省份 下拉列表 2. 当 页面加载完成后 发送ajax请求,加载所有省份 注意:使用redis缓存一些不经常发生变化的数据。* 数据库的数据一旦发生改变,则需要更新缓存。 * 数据库的表执行 增删改的相关操作,需要将redis缓存数据情况,再次存入 * 在service对应的增删改方法中,将redis数据删除。]]></content>
<categories>
<category>非关系型数据库</category>
</categories>
<tags>
<tag>Redis</tag>
</tags>
</entry>
<entry>
<title><![CDATA[二、Spring Boot配置文件详解:Properties和YAML]]></title>
<url>%2F2019%2F08%2F23%2F%E4%BA%8C%E3%80%81Spring-Boot%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%AF%A6%E8%A7%A3%EF%BC%9AProperties%E5%92%8CYAML%2F</url>
<content type="text"><![CDATA[Spring Boot配置文件详解:Properties和YAML一.配置文件的生效顺序,会对值进行覆盖: @TestPropertySource 注解 命令行参数 Java系统属性(System.getProperties()) 操作系统环境变量 只有在random.*里包含的属性会产生一个RandomValuePropertySource 在properties文件中设置随机值,随机数等 123456789101112131415161718192021222324252627#这个优先级较低#32位随机字符串roncoo.secret=${random.value}#int类型的随机数字roncoo.number=${random.int}roncoo.name=www.roncoo.com#属性占位符属性roncoo.desc=${roncoo.name} is a domain name#应用端口server.port=8090#时间格式化spring.jackson.date-format=yyyy-MM-dd HH:mm:ss#时区设置spring.jackson.time-zone=Asia/Chongqing 在IndexController层中获取 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152package com.roncoo.education.controller;import java.util.Date;import java.util.HashMap;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.roncoo.education.bean.User;/** * spring-boot-demo-3-1 * * @author wujing */@RestController@RequestMapping(value = "/index")public class IndexController { @Value(value = "${roncoo.secret}") private String secret; @Value(value = "${roncoo.number}") private int id; @Value(value = "${roncoo.desc}") private String desc; @RequestMapping public String index() { return "hello world"; } // @RequestParam 简单类型的绑定,可以出来get和post @RequestMapping(value = "/get") public HashMap<String, Object> get(@RequestParam String name) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title", "hello world"); map.put("name", name); map.put("secret", secret); map.put("id", id); map.put("desc", desc); return map; } // @PathVariable 获得请求url中的动态参数 @RequestMapping(value = "/get/{id}/{name}") public User getUser(@PathVariable int id, @PathVariable String name) { User user = new User(); user.setId(id); user.setName(name); user.setDate(new Date()); return user; }} 二.配置随机值roncoo.secret=${random.value} roncoo.number=${random.int} roncoo.bignumber=${random.long} roncoo.number.less.than.ten=${random.int(10)} roncoo.number.in.range=${random.int[1024,65536]} 读取使用注解:@Value(value = “${roncoo.secret}”) 注:出现黄点提示,是要提示配置元数据,可以不配置 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量) 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量) 在@Configuration类上的@PropertySource注解 默认属性(使用SpringApplication.setDefaultProperties指定) 三.属性占位符当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。 roncoo.name=www.roncoo.com roncoo.desc=${roncoo.name} is a domain name 四.Application属性文件,按优先级排序,位置高的将覆盖位置低的 当前目录下的一个/config子目录 当前目录 一个classpath下的/config包 classpath根路径(root) 这个列表是按优先级排序的(列表中位置高的将覆盖位置低的) 五. 配置应用端口和其他配置的介绍#端口配置: server.port=8090 #时间格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #时区设置 spring.jackson.time-zone=Asia/Chongqing 六. 使用YAML代替Properties注意写法:冒号后要加个空格]]></content>
<categories>
<category>Spring Boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[一篇文章,教你学会Git]]></title>
<url>%2F2019%2F08%2F23%2F%E4%B8%80%E7%AF%87%E6%96%87%E7%AB%A0%EF%BC%8C%E6%95%99%E4%BD%A0%E5%AD%A6%E4%BC%9AGit%2F</url>
<content type="text"><![CDATA[一篇文章,教你学会Git 在日常工作中,经常会用到Git操作。但是对于新人来讲,刚上来对Git很陌生,操作起来也很懵逼。本篇文章主要针对刚开始接触Git的新人,理解Git的基本原理,掌握常用的一些命令。 一、Git工作流程 以上包括一些简单而常用的命令,但是先不关心这些,先来了解下面这4个专有名词。 Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remote:远程仓库 工作区 程序员进行开发改动的地方,是你当前看到的,也是最新的。 平常我们开发就是拷贝远程仓库中的一个分支,基于该分支进行开发。在开发过程中就是对工作区的操作。 暂存区 .git目录下的index文件, 暂存区会记录git add添加文件的相关信息(文件名、大小、timestamp…),不保存文件实体, 通过id指向每个文件实体。可以使用git status查看暂存区的状态。暂存区标记了你当前工作区中,哪些内容是被git管理的。 当你完成某个需求或功能后需要提交到远程仓库,那么第一步就是通过git add先提交到暂存区,被git管理。 本地仓库 保存了对象被提交 过的各个版本,比起工作区和暂存区的内容,它要更旧一些。 git commit后同步index的目录树到本地仓库,方便从下一步通过git push同步本地仓库与远程仓库的同步。 远程仓库 远程仓库的内容可能被分布在多个地点的处于协作关系的本地仓库修改,因此它可能与本地仓库同步,也可能不同步,但是它的内容是最旧的。 小结 任何对象都是在工作区中诞生和被修改; 任何修改都是从进入index区才开始被版本控制; 只有把修改提交到本地仓库,该修改才能在仓库中留下痕迹; 与协作者分享本地的修改,可以把它们push到远程仓库来共享。 下面这幅图更加直接阐述了四个区域之间的关系,可能有些命令不太清楚,没关系,下部分会详细介绍。 二、常用Git命令 网上找了个图,别人整理的一张图,很全很好,借来用下。下面详细解释一些常用命令。 HEAD 在掌握具体命令前,先理解下HEAD。 HEAD,它始终指向当前所处分支的最新的提交点。你所处的分支变化了,或者产生了新的提交点,HEAD就会跟着改变。 add add相关命令很简单,主要实现将工作区修改的内容提交到暂存区,交由git管理。 git add . 添加当前目录的所有文件到暂存区 git add 添加指定目录到暂存区,包括子目录 git add 添加指定文件到暂存区 commit commit相关命令也很简单,主要实现将暂存区的内容提交到本地仓库,并使得当前分支的HEAD向后移动一个提交点。 git commit -m 提交暂存区到本地仓库,message代表说明信息 git commit -m 提交暂存区的指定文件到本地仓库 git commit –amend -m 使用一次新的commit,替代上一次提交 branch 涉及到协作,自然会涉及到分支,关于分支,大概有展示分支,切换分支,创建分支,删除分支这四种操作。 git branch 列出所有本地分支 git branch -r 列出所有远程分支 git branch -a 列出所有本地分支和远程分支 git branch 新建一个分支,但依然停留在当前分支 git checkout -b 新建一个分支,并切换到该分支 git branch –track 新建一个分支,与指定的远程分支建立追踪关系 git checkout 切换到指定分支,并更新工作区 git branch -d 删除分支 git push origin –delete 删除远程分支 关于分支的操作虽然比较多,但都比较简单好记。 merge merge命令把不同的分支合并起来。如上图,在实际开放中,我们可能从master分支中切出一个分支,然后进行开发完成需求,中间经过R3,R4,R5的commit记录,最后开发完成需要合入master中,这便用到了merge。 git fetch merge之前先拉一下远程仓库最新代码 git merge 合并指定分支到当前分支 一般在merge之后,会出现conflict,需要针对冲突情况,手动解除冲突。主要是因为两个用户修改了同一文件的同一块区域。如下图所示,需要手动解除。 rebase rebase又称为衍合,是合并的另外一种选择。 在开始阶段,我们处于new分支上,执行git rebase dev,那么new分支上新的commit都在master分支上重演一遍,最后checkout切换回到new分支。这一点与merge是一样的,合并前后所处的分支并没有改变。git rebase dev,通俗的解释就是new分支想站在dev的肩膀上继续下去。rebase也需要手动解决冲突。 rebase与merge的区别 现在我们有这样的两个分支,test和master,提交如下: 123456789D---E test /A---B---C---F master 在master执行git merge test,然后会得到如下结果: 123456789D--------E / \A---B---C---F----G test, master 在master执行git rebase test,然后得到如下结果: 1A---B---D---E---C'---F' test, master 可以看到,merge操作会生成一个新的节点,之前的提交分开显示。而rebase操作不会生成新的节点,是将两个分支融合成一个线性的提交。 如果你想要一个干净的,没有merge commit的线性历史树,那么你应该选择git rebase如果你想保留完整的历史记录,并且想要避免重写commit history的风险,你应该选择使用git merge reset reset命令把当前分支指向另一个位置,并且相应的变动工作区和暂存区。 git reset —soft 只改变提交点,暂存区和工作目录的内容都不改变 git reset —mixed 改变提交点,同时改变暂存区的内容 git reset —hard 暂存区、工作区的内容都会被修改到与提交点完全一致的状态 git reset –hard HEAD 让工作区回到上次提交时的状态 revert git revert用一个新提交来消除一个历史提交所做的任何修改。 revert与reset的区别 git revert是用一次新的commit来回滚之前的commit,git reset是直接删除指定的commit。 在回滚这一操作上看,效果差不多。但是在日后继续merge以前的老版本时有区别。因为git revert是用一次逆向的commit“中和”之前的提交,因此日后合并老的branch时,导致这部分改变不会再次出现,减少冲突。但是git reset是之间把某些commit在某个branch上删除,因而和老的branch再次merge时,这些被回滚的commit应该还会被引入,产生很多冲突。关于这一点,不太理解的可以看这篇文章。 git reset 是把HEAD向后移动了一下,而git revert是HEAD继续前进,只是新的commit的内容和要revert的内容正好相反,能够抵消要被revert的内容。 push上传本地仓库分支到远程仓库分支,实现同步。 git push 上传本地指定分支到远程仓库 git push –force 强行推送当前分支到远程仓库,即使有冲突 git push –all 推送所有分支到远程仓库 其他命令 git status 显示有变更的文件 git log 显示当前分支的版本历史 git diff 显示暂存区和工作区的差异 git diff HEAD 显示工作区与当前分支最新commit之间的差异 git cherry-pick 选择一个commit,合并进当前分支 以上就是关于Git的一些常用命令及详细阐述,相信能对Git有一个初步的认识。]]></content>
<categories>
<category>Git管理工具</category>
</categories>
<tags>
<tag>Git</tag>
</tags>
</entry>
<entry>
<title><![CDATA[Spring Boot RESTfull API简单项目的快速搭建]]></title>
<url>%2F2019%2F08%2F23%2F%E4%B8%80%E3%80%81Spring%20Boot%20RESTfull-API%E7%AE%80%E5%8D%95%E9%A1%B9%E7%9B%AE%E7%9A%84%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BA%2F</url>
<content type="text"><![CDATA[Spring Boot RESTfull API简单项目的快速搭建对spring框架盛行了多年的java方向开发人员来说,每个人java开发已经把spring框架当做开发中不可或缺的一部分。之前传统的模式都是以applicationContext.xml配置文件的形式存在,而对应大多数入门级开发人员来说配置出现一点纰漏就会导致运行失败或者更大的问题,因此会浪费开发人员很多宝贵的时间,对公司来说也是有所损失。那么spring开源组织很早之前就意识到这种问题的存在,于是他们便对spring框架的全系列组件进行了内部封装。对外只是提供maven(jar管理、项目打包工具)或者gradle(新兴jar管理、项目打包工具)的形式来进行引入parent.pom(maven配置文件)或者parent.gradle(gradle配置文件),让每一个spring项目都是以spring的子项目的形式来运行,这样开发人员不用再去注重配置文件的繁琐而是把精力放到业务逻辑以及更深层次的架构方面。自此SpringBoot就诞生了,它有着纯正的开源血统,在此非常感谢spring开源组织给我们java开发人员带来的便利! SpringBoot主要优点: 为所有Spring开发者更快的入门 开箱即用,提供各种默认配置来简化项目配置 内嵌式容器简化Web项目 没有冗余代码生成和XML配置的要求 提供一系列大型企业级项目的功能性特性(比如:安全、健康检测、外部化配置、数据库访问、restful搭建等很多特性这里就不一一叙说了,后期文章会陆续更新) 本章目的使用springboot完成一个简单的web(springmvc)应用程序,通过@restController输出”HelloWord”到界面,让我们初步体验springboot的快速开发、简单的特性。 系统要求 jdk1.8 springboot 1.5.2.RELEASE 开发工具(IntelliJ IDEA 2017.1.1) 数据库管理工具(Navicat Premium 11.1.7) 文本管理工具(sublime text 3) apache maven(3.3.9,本章采用maven形式管理jar包,具体配置环境变量以及使用请自行查找资料) 开始构建项目目前构建项目有多种方式我这里简单介绍两种。1、使用spring官网 SPRING INITIALIZR 来构建项目结构(地址:http://start.spring.io/)2、使用IntelliJ IDEA开发工具来构建项目结构 使用SPRING INITIALIZR构建访问start.spring.io/网址就会看到如下 “图1” 界面:界面主要部分包括:管理工具,springboot版本,包名(group),工程名(Artifact),已选模块(我已经选择了一个web模块)。点击Generate Project就会下载一个根据你输入的信息创建的项目工程架构源码的压缩包。解压压缩包到指定目录(目录你可以随意定义)我这里为了后续操作先定义到E:/lessions内可以看到如下“图2”所示:解压完成之后我们就可以通过IntelliJ IDEA开发工具导入到工程, 菜单中选择File–>New–>Project from Existing Sources… 选择解压后的项目文件夹,点击OK 点击Import project from external model并选择Maven,点击Next到底为止。 若你的环境有多个版本的JDK,注意到选择Java SDK的时候请选择系统安装1.8版本 使用IntelliJ IDEA构建打开工具,界面如下 “图3” 所示:我们点击Create New Project来创建一个新的springboot应用程序,点击后如下“图4”所示:我们点击Next继续下一步操作,根据界面输入选项填写对应的内容即可如“图5”所示:点击Next即可完成创建项目,而且创建完成后会自动导入到项目工程内就不需要再次import操作,这种方式会比较简单些,所以我们的文章内都会采用第二种形式来创建新工程。 在下一步我们勾选Web依赖加入到我们的项目中,如下图所示: 项目目录结构我们来看看工具为我们生成新工程的目录结构,如”图6“所示:我们可以看到目录结构有如下几个: 1、/src/main/java/ 存放项目所有源代码目录2、/src//main/resources/ 存放项目所有资源文件以及配置文件目录3、/src/test/ 存放测试代码目录 自动生成的文件解释SpringBoot21Application 该类是程序的入口类内有个main方法,可以直接通过run as运行项目application.properties 该配置文件是项目的核心配置文件,以xx.xx.xx的形式存在pom.xml maven配置文件,因为我们采用的maven管理jar,所以这里会自动生成一个pom文件 @SpringBootApplication注解我们可以看到工具为我们自动生成的入口程序是有@SpringBootApplication的这么一个注解,那它主要是做什么的呢?不难看出,它是声明当前类为sprinboot的入口类。而一个springboot项目内有且只能有一个这个注解存在。 初尝试运行项目我们在入口程序类中右键->Run LessonOneApplication在控制台的输出如下”图8“所示,证明你已经成功的运行了springboot项目。 可以看到我们的项目是通过内置的tomcat容器启动的,并且端口号默认是8080(至于如何修改端口号后期文章中更新)。我们现在通过浏览器直接访问是得不到任何回应的,只是会有一个错误页面,如下”图9“所示 编写IndexController我们首先在/src/main/java/com/lqg (该目录是你构建项目的目录) 目录下创建一个叫做controller的包,然后在controller包下再创建一个叫做IndexController的类,我们使用@RestController来声明我们新创建的IndexController是一个访问控制器,详细代码如下: 1234567891011121314package com.lqg.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping(value = "/index")public class IndexController { @RequestMapping public String index(){ return "hello spring boot"; }}12345678910111213 可以看到我在IndexController类上配置了一个@RequestMapping注解来声明index()方法可以通过127.0.0.1:8080/index访问到,那么我们接下来重新启动项目(项目中如果重启出错应该是注解配置问题),访问地址如下”图10“所示:在IndexController类里面在写一个方法,返回值是map集合,参数列表是String类型的name,@RequestParam简单类型的绑定的注解,这个注解要放在参数列表的前面 1234567891011121314151617181920212223242526272829303132package com.lqg.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;@RestController@RequestMapping(value = "/index")public class IndexController { @RequestMapping public String hello(){ return "hello spring boot "; } /** * @RequestParam 简单类型的绑定,可以出来get和post * @param name * @return */ @RequestMapping(value = "/get") public HashMap<String,Object> get(@RequestParam String name){ HashMap<String,Object> map = new HashMap<>(); map.put("title", "hello world"); map.put("name", name); return map; }}12345678910111213141516171819202122232425262728293031 那么Controller层是如何返回一个Bean对象呢?先在/src/main/java/com/lqg下面创建一个bean包,在bean包里创建一个User类,详细代码如下: 1234567891011121314151617181920package com.lqg.bean;import lombok.Getter;import lombok.Setter;import java.util.Date;/** * @author 凌枫lqg */@Getter@Setterpublic class User { private int id; private String name; private Date date;}12345678910111213141516171819 @Getter@Setter:注解是lombok插件里面的,用这个注解就可以省略getter和setter方法 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950package com.lqg.controller;import com.lqg.bean.User;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.xml.crypto.Data;import java.util.Date;import java.util.HashMap;@RestController@RequestMapping(value = "/index")public class IndexController { @RequestMapping public String hello(){ return "hello spring boot "; } /** * @RequestParam 简单类型的绑定,可以出来get和post * @param name * @return */ @RequestMapping(value = "/get") public HashMap<String,Object> get(@RequestParam String name){ HashMap<String,Object> map = new HashMap<>(); map.put("title", "hello world"); map.put("name", name); return map; } /** * @PathVariable 获得请求url中的动态参数 * @param id * @param name * @return */ @RequestMapping(value = "/find/{id}/{name}") public User get(@PathVariable int id,@PathVariable String name){ User user = new User(); user.setId(id); user.setName(name); user.setDate(new Date()); return user; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 第二个方法访问的结果如下第三个方法访问的结果如下: SpringBoot的测试SpringBoot测试可以通过Spring提供的测试类MockMvc 1234567891011121314151617181920212223242526272829303132333435363738394041package com.lqg;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import com.lqg.controller.IndexController;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.RequestBuilder;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import com.lqg.controller.IndexController;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootDemo21ApplicationTests { //SpringBoot测试可以通过Spring提供的测试类MockMvc private MockMvc mvc; @Before public void setup() { //这是通过setup方法引入mvc this.mvc = MockMvcBuilders.standaloneSetup(new IndexController()).build(); } @Test public void contextLoads() throws Exception { //生成request一个请求 RequestBuilder request = get("/index"); //用mvc的请求,期望它的状态码是ok的,期望它返回的内容,返回的是一个字符串hello spring boot mvc.perform(request).andExpect(status().isOk()).andExpect(content().string("hello spring boot")); }}12345678910111213141516171819202122232425262728293031323334353637383940 SpringBoot打包 打包成功后的jar包,打包命令mvn clean install -DskipTests 在命令行运行spring boot]]></content>
<categories>
<category>spring boot</category>
</categories>
<tags>
<tag>Spring Boot</tag>
</tags>
</entry>
<entry>
<title><![CDATA[idea中如何导入mysql驱动包]]></title>
<url>%2F2019%2F08%2F23%2Fidea%E4%B8%AD%E5%A6%82%E4%BD%95%E5%AF%BC%E5%85%A5mysql%E9%A9%B1%E5%8A%A8%E5%8C%85%2F</url>
<content type="text"><![CDATA[IDEA怎样导入mysql的驱动包注:刚开始用用csdn写博文,写的不好,还请各位博客好友见谅,也可以互相提意见,共同进步!首先需要有mysql的驱动包,没有可以在mysql官网下载 有了驱动包后,就开始进入怎样用IDEA导入mysql驱动包了 1. 打开你的idea工程,点击File2.找到Project Structure并点击3.找到Modules并点击4.找到Dependencies并点击2.找到Project Structure并点击5.找到Scope右边的+号并点击2.选第一个JARs or directories,找到文件mysql-connector-java-版本号-bin.jar,然后点击ok就成功了]]></content>
<categories>
<category>数据库</category>
</categories>
<tags>
<tag>mysql</tag>
</tags>
</entry>
<entry>
<title><![CDATA[2019最新的解决百度网盘下载限速的方法,不限速下载百度云破解版]]></title>
<url>%2F2019%2F08%2F23%2F2019%E6%9C%80%E6%96%B0%E7%9A%84%E8%A7%A3%E5%86%B3%E7%99%BE%E5%BA%A6%E7%BD%91%E7%9B%98%E4%B8%8B%E8%BD%BD%E9%99%90%E9%80%9F%E7%9A%84%E6%96%B9%E6%B3%95%EF%BC%8C%E4%B8%8D%E9%99%90%E9%80%9F%E4%B8%8B%E8%BD%BD%E7%99%BE%E5%BA%A6%E4%BA%91%E7%A0%B4%E8%A7%A3%E7%89%88%2F</url>
<content type="text"><![CDATA[2019最新的解决百度网盘下载限速的方法,不限速下载百度云破解版下载地址,点击下载,提取码:c25f 永久有效https://pan.baidu.com/s/1G2X8diMTPzTyC_oOvgkyWw 不限速下载以下为软件使用教程,必看 软件使用教程:首先:在打开软件以后先观察是否弹出更新提示,如果有更新提示则必须要更新,一般选择在线自动更新。 第一步,把压缩包下载并解压到你的电脑上,但不要解压到C盘和桌面上。解压完成以后文件夹里的文件如图所示图中用红圈圈出来的文件就是运行的主程序第二步:点击红框中的文件会出现下图中的样子第三步:然后登陆自己的网盘账号以后开始下载情况1、下载自己网盘里的东西 登录之后找到你网盘里的想要下载的文件(不要直接点下载),点击“分享并下载”,然后再确认下载就OK了。 情况2、如果下载在别处获得的链接,请在“下载”栏目下面的“下载分享链接”处下载。如果出现无限验证码或其他错误也可以先保存到自己网盘,然后用1中的方法。软件非常好用,需要的同学可以点击下载了:链接:https://pan.baidu.com/s/1G2X8diMTPzTyC_oOvgkyWw> 提取码:c25f 永久有效]]></content>
<categories>
<category>百度云</category>
</categories>
<tags>
<tag>baiduyun</tag>
</tags>
</entry>
</search>