-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy paththymeleafspring.html
More file actions
1224 lines (1134 loc) · 78.2 KB
/
thymeleafspring.html
File metadata and controls
1224 lines (1134 loc) · 78.2 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tutorial: Thymeleaf + Spring</title>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="format-detection" content="telephone=no"/>
<link rel="icon" href="../../images/favicon.ico"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:400,400italic,700,700italic"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic,700italic"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/2.1.3/normalize.min.css" media="screen"/>
<link rel="stylesheet" href="../../styles/thymeleaf.css"/>
<link rel="stylesheet" href="../../styles/thymeleaf-tutorials.css"/>
<link rel="stylesheet" href="../../styles/thymeleaf-tutorials-screen.css" media="screen"/>
<link rel="stylesheet" href="../../styles/thymeleaf-tutorials-print.css" media="print"/>
<script src="https://unpkg.com/dumb-query-selector@3.0.0/dumb-query-selector.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/components/prism-core.min.js" defer data-manual></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/components/prism-markup.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/components/prism-clike.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/components/prism-java.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/plugins/line-numbers/prism-line-numbers.min.js" defer></script>
<script src="../../scripts/thymeleaf-tutorials.js" defer></script>
</head>
<body class="tutorial">
<div class="toc-wrapper toolbar-container">
<div class="toolbar-menu">
<div id="toolbar-location" class="toolbar-menu-location"></div>
<button id="site-menu-button" type="button" class="toolbar-menu-button">Doc Contents</button>
</div>
<nav id="toc">
<ul>
<li><a href="#preface">Preface</a></li>
<li><a href="#integrating-thymeleaf-with-spring">1 Integrating Thymeleaf with Spring</a></li>
<li><a href="#the-springstandard-dialect">2 The SpringStandard Dialect</a></li>
<li><a href="#views-and-view-resolvers">3 Views and View Resolvers</a><ul>
<li><a href="#views-and-view-resolvers-in-spring-mvc">3.1 Views and View Resolvers in Spring MVC</a></li>
<li><a href="#views-and-view-resolvers-in-thymeleaf">3.2 Views and View Resolvers in Thymeleaf</a></li>
</ul></li>
<li><a href="#spring-thyme-seed-starter-manager">4 Spring Thyme Seed Starter Manager</a><ul>
<li><a href="#the-concept">4.1 The Concept</a></li>
<li><a href="#business-layer">4.2 Business Layer</a></li>
<li><a href="#spring-mvc-configuration">4.3 Spring MVC configuration</a></li>
<li><a href="#the-controller">4.4 The Controller</a><ul>
<li><a href="#model-attributes">Model Attributes</a></li>
<li><a href="#mapped-methods">Mapped methods</a></li>
</ul></li>
<li><a href="#configuring-a-conversion-service">4.5 Configuring a Conversion Service</a></li>
</ul></li>
<li><a href="#listing-seed-starter-data">5 Listing Seed Starter Data</a></li>
<li><a href="#creating-a-form">6 Creating a Form</a><ul>
<li><a href="#handling-the-command-object">6.1 Handling the command object</a></li>
<li><a href="#inputs">6.2 Inputs</a></li>
<li><a href="#checkbox-fields">6.3 Checkbox fields</a></li>
<li><a href="#radio-button-fields">6.4 Radio Button fields</a></li>
<li><a href="#dropdownlist-selectors">6.5 Dropdown/List selectors</a></li>
<li><a href="#dynamic-fields">6.6 Dynamic fields</a></li>
</ul></li>
<li><a href="#validation-and-error-messages">7 Validation and Error Messages</a><ul>
<li><a href="#field-errors">7.1 Field errors</a><ul>
<li><a href="#simplifying-error-based-css-styling-therrorclass">Simplifying error-based CSS styling: <code>th:errorclass</code></a></li>
</ul></li>
<li><a href="#all-errors">7.2 All errors</a></li>
<li><a href="#global-errors">7.3 Global errors</a></li>
<li><a href="#displaying-errors-outside-forms">7.4 Displaying errors outside forms</a></li>
<li><a href="#rich-error-objects">7.5 Rich error objects</a></li>
</ul></li>
<li><a href="#its-still-a-prototype">8 It’s still a Prototype!</a></li>
<li><a href="#the-conversion-service">9 The Conversion Service</a><ul>
<li><a href="#configuration">9.1 Configuration</a></li>
<li><a href="#double-brace-syntax">9.1 Double-brace syntax</a></li>
<li><a href="#use-in-forms">9.2 Use in forms</a></li>
<li><a href="#conversions-utility-object">9.3 <code>#conversions</code> utility object</a></li>
</ul></li>
<li><a href="#rendering-template-fragments">10 Rendering Template Fragments</a><ul>
<li><a href="#specifying-fragments-in-view-beans">10.1 Specifying fragments in view beans</a></li>
<li><a href="#specifying-fragments-in-controller-return-values">10.2 Specifying fragments in controller return values</a></li>
</ul></li>
<li><a href="#advanced-integration-features">11 Advanced Integration Features</a><ul>
<li><a href="#integration-with-requestdatavalueprocessor">11.1 Integration with <code>RequestDataValueProcessor</code></a></li>
<li><a href="#building-uris-to-controllers">11.1 Building URIs to controllers</a></li>
</ul></li>
<li><a href="#spring-webflow-integration">12 Spring WebFlow integration</a><ul>
<li><a href="#basic-configuration">12.1 Basic configuration</a></li>
<li><a href="#ajax-fragments-in-spring-webflow">12.2 AJAX fragments in Spring WebFlow</a></li>
</ul></li>
</ul>
</nav>
</div>
<div class="content-wrapper">
<div class="title-container">
<header class="hero-header fluid-block">
<div class="hero-header-text">
<h1 class="hero-header-title">Thymeleaf</h1>
</div>
<div class="hero-header-image">
<img src="../../images/thymeleaf.png" alt="Thymeleaf logo" class="hero-header-logo"/>
</div>
</header>
<div class="tutorial-info fluid-block">
<h1 id="tutorial-title" class="tutorial-title">Tutorial: Thymeleaf + Spring</h1>
<div class="tutorial-metadata">
<div id="tutorial-version">
<span class="tutorial-metadata-label">Document version:</span> 20181029 - 29 October 2018
</div>
<div id="project-version">
<span class="tutorial-metadata-label">Project version:</span> 3.0.11.RELEASE
</div>
<div id="project-website">
<span class="tutorial-metadata-label">Project web site:</span>
<a href="https://www.thymeleaf.org">https://www.thymeleaf.org</a>
</div>
</div>
</div>
</div>
<div id="content" class="fluid-block">
<section id="preface" class="level1">
<h1>Preface</h1>
<p>This tutorial explains how Thymeleaf can be integrated with the Spring Framework, especially (but not only) Spring MVC.</p>
<p>Note that Thymeleaf has integrations for both versions 3.x and 4.x of the Spring Framework, provided by two separate libraries called <code>thymeleaf-spring3</code> and <code>thymeleaf-spring4</code>. These libraries are packaged in separate <code>.jar</code> files (<code>thymeleaf-spring3-{version}.jar</code> and <code>thymeleaf-spring4-{version}.jar</code>) and need to be added to your classpath in order to use Thymeleaf’s Spring integrations in your application.</p>
<p>The code samples and example application in this tutorial make use of <strong>Spring 4.x</strong> and its corresponding Thymeleaf integrations, but the contents of this text are valid also for Spring 3.x. If your application uses Spring 3.x, all you have to do is replace the <code>org.thymeleaf.spring4</code> package with <code>org.thymeleaf.spring3</code> in the code samples.</p>
</section>
<section id="integrating-thymeleaf-with-spring" class="level1">
<h1>1 Integrating Thymeleaf with Spring</h1>
<p>Thymeleaf offers a set of Spring integrations that allow you to use it as a fully-featured substitute for JSP in Spring MVC applications.</p>
<p>These integrations will allow you to:</p>
<ul>
<li>Make the mapped methods in your Spring MVC <code>@Controller</code> objects forward to templates managed by Thymeleaf, exactly like you do with JSPs.</li>
<li>Use <strong>Spring Expression Language</strong> (Spring EL) instead of OGNL in your templates.</li>
<li>Create forms in your templates that are completely integrated with your form-backing beans and result bindings, including the use of property editors, conversion services and validation error handling.</li>
<li>Display internationalization messages from message files managed by Spring (through the usual <code>MessageSource</code> objects).</li>
<li>Resolve your templates using Spring’s own resource resolution mechanisms.</li>
</ul>
<p>Note that in order to fully understand this tutorial, you should have first gone through the <a href="https://www.thymeleaf.org/documentation.html#using-thymeleaf"><em>“Using Thymeleaf”</em></a> tutorial, which explains the Standard Dialect in depth.</p>
</section>
<section id="the-springstandard-dialect" class="level1">
<h1>2 The SpringStandard Dialect</h1>
<p>In order to achieve an easier and better integration, Thymeleaf provides a dialect which specifically implements all the needed features for it to work correctly with Spring.</p>
<p>This specific dialect is based on the Thymeleaf Standard Dialect and is implemented in a class called <code>org.thymeleaf.spring4.dialect.SpringStandardDialect</code>, which in fact extends from <code>org.thymeleaf.standard.StandardDialect</code>.</p>
<p>Besides all the features already present in the Standard Dialect –and therefore inherited–, the SpringStandard Dialect introduces the following specific features:</p>
<ul>
<li>Use Spring Expression Language (Spring EL or SpEL) as a variable expression language, instead of OGNL. Consequently, all <code>${...}</code> and <code>*{...}</code> expressions will be evaluated by Spring’s Expression Language engine. Note also that support for the Spring EL compiler is available (Spring 4.2.4+).</li>
<li>Access any beans in your application context using SpringEL’s syntax: <code>${@myBean.doSomething()}</code></li>
<li>New attributes for form processing: <code>th:field</code>, <code>th:errors</code> and <code>th:errorclass</code>, besides a new implementation of <code>th:object</code> that allows it to be used for form command selection.</li>
<li>An expression object and method, <code>#themes.code(...)</code>, which is equivalent to the <code>spring:theme</code> JSP custom tag.</li>
<li>An expression object and method, <code>#mvc.uri(...)</code>, which is equivalent to the <code>spring:mvcUrl(...)</code> JSP custom function (only in Spring 4.1+).</li>
</ul>
<p>Note that most of the times <em>you shouldn’t be using this dialect directly in a normal <code>TemplateEngine</code> object</em> as a part of its configuration. Unless you have very specific Spring integration needs, you should instead be creating an instance of a new template engine class that performs all the required configuration steps automatically: <code>org.thymeleaf.spring4.SpringTemplateEngine</code>.</p>
<p>An example bean configuration:</p>
<pre class="java"><code>@Bean
public SpringResourceTemplateResolver templateResolver(){
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// Enabling the SpringEL compiler with Spring 4.2.4 or newer can
// speed up execution in most scenarios, but might be incompatible
// with specific cases when expressions in one template are reused
// across different data types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}</code></pre>
<p>Or, using Spring’s XML-based configuration:</p>
<pre class="xml"><code><!-- SpringResourceTemplateResolver automatically integrates with Spring's own -->
<!-- resource resolution infrastructure, which is highly recommended. -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<!-- HTML is the default value, added here for the sake of clarity. -->
<property name="templateMode" value="HTML" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="true" />
</bean>
<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
<!-- enables Spring's own MessageSource message resolution mechanisms. -->
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed up -->
<!-- execution in most scenarios, but might be incompatible with specific -->
<!-- cases when expressions in one template are reused across different data -->
<!-- ypes, so this flag is "false" by default for safer backwards -->
<!-- compatibility. -->
<property name="enableSpringELCompiler" value="true" />
</bean></code></pre>
</section>
<section id="views-and-view-resolvers" class="level1">
<h1>3 Views and View Resolvers</h1>
<section id="views-and-view-resolvers-in-spring-mvc" class="level2">
<h2>3.1 Views and View Resolvers in Spring MVC</h2>
<p>There are two interfaces in Spring MVC that conform the core of its templating system:</p>
<ul>
<li><code>org.springframework.web.servlet.View</code></li>
<li><code>org.springframework.web.servlet.ViewResolver</code></li>
</ul>
<p>Views model pages in our applications and allow us to modify and predefine their behaviour by defining them as beans. Views are in charge of rendering the actual HTML interface, usually by the execution of some template engine like Thymeleaf.</p>
<p>ViewResolvers are the objects in charge of obtaining View objects for a specific operation and locale. Typically, controllers ask ViewResolvers to forward to a view with a specific name (a String returned by the controller method), and then all the view resolvers in the application execute in ordered chain until one of them is able to resolve that view, in which case a View object is returned and control is passed to it for the renderization of HTML.</p>
<blockquote>
<p>Note that not all pages in our applications have to be defined as Views, but only those which behaviour we wish to be non-standard or configured in a specific way (for example, by wiring some special beans to it). If a ViewResolver is asked a view that has no corresponding bean –which is the common case–, a new View object is created ad hoc and returned.</p>
</blockquote>
<p>A typical configuration for a JSP+JSTL ViewResolver in a Spring MVC application from the past looked like this:</p>
<pre class="xml"><code><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsps/" />
<property name="suffix" value=".jsp" />
<property name="order" value="2" />
<property name="viewNames" value="*jsp" />
</bean></code></pre>
<p>A quick look at its properties is enough to know about how it was configured:</p>
<ul>
<li><code>viewClass</code> establishes the class of the View instances. This is needed for a JSP resolver, but it will not be needed at all when we’re working with Thymeleaf.</li>
<li><code>prefix</code> and <code>suffix</code> work in a similar way to the attributes of the same names in Thymeleaf’s TemplateResolver objects.</li>
<li><code>order</code> establishes the order in which the ViewResolver will be queried in the chain.</li>
<li><code>viewNames</code> allows the definition (with wildcards) of the view names that will be resolved by this ViewResolver.</li>
</ul>
</section>
<section id="views-and-view-resolvers-in-thymeleaf" class="level2">
<h2>3.2 Views and View Resolvers in Thymeleaf</h2>
<p>Thymeleaf offers implementations for the two interfaces mentioned above:</p>
<ul>
<li><code>org.thymeleaf.spring4.view.ThymeleafView</code></li>
<li><code>org.thymeleaf.spring4.view.ThymeleafViewResolver</code></li>
</ul>
<p>These two classes will be in charge of processing Thymeleaf templates as a result of the execution of controllers.</p>
<p>Configuration of the Thymeleaf View Resolver is very similar to that of JSP:</p>
<pre class="java"><code>@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
// NOTE 'order' and 'viewNames' are optional
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[] {".html", ".xhtml"});
return viewResolver;
}</code></pre>
<p>…or in XML:</p>
<pre class="xml"><code><bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<!-- NOTE 'order' and 'viewNames' are optional -->
<property name="order" value="1" />
<property name="viewNames" value="*.html,*.xhtml" />
</bean></code></pre>
<p>The <code>templateEngine</code> parameter is, of course, the <code>SpringTemplateEngine</code> object we defined in the previous chapter. The other two (<code>order</code> and <code>viewNames</code>) are both optional, and have the same meaning as in the JSP ViewResolver we saw before.</p>
<p>Note that we do not need <code>prefix</code> or <code>suffix</code> parameters, because these are already specified at the Template Resolver (which in turn is passed to the Template Engine).</p>
<p>And what if we wanted to define a <code>View</code> bean and add some static variables to it? Easy, just define a <em>prototype</em> bean for it:</p>
<pre class="java"><code>@Bean
@Scope("prototype")
public ThymeleafView mainView() {
ThymeleafView view = new ThymeleafView("main"); // templateName = 'main'
view.setStaticVariables(
Collections.singletonMap("footer", "The ACME Fruit Company"));
return view;
}</code></pre>
<p>By doing this, you will be able to execute specifically this view bean selecting it by bean name (<code>mainView</code>, in this case).</p>
</section>
</section>
<section id="spring-thyme-seed-starter-manager" class="level1">
<h1>4 Spring Thyme Seed Starter Manager</h1>
<p>The source code for the examples shown in this and future chapters of this guide can be found in the <a href="https://github.com/thymeleaf/thymeleafexamples-stsm">Spring Thyme Seed Starter Manager GitHub repository</a>.</p>
<section id="the-concept" class="level2">
<h2>4.1 The Concept</h2>
<p>At Thymeleaf we’re huge fans of thyme, and every spring we prepare our seed starting kits with good soil and our favourite seeds, place them under the Spanish sun and patiently wait for our new plants to grow.</p>
<p>But this year we got fed up with sticking labels to the seed starter containers for knowing which seed was in each cell of the container, so we decided to prepare an application using Spring MVC and Thymeleaf to help us catalogue our starters: <em>The Spring Thyme SeedStarter Manager</em>.</p>
<figure>
<img src="images/thymeleafspring/stsm-view.png" alt="STSM front page" /><figcaption>STSM front page</figcaption>
</figure>
<p>In a similar way to the Good Thymes Virtual Grocery application we developed in the <em>Using Thymeleaf</em> tutorial, the STSM will allow us to exemplify the most important aspects of the integration of Thymeleaf as a template engine for Spring MVC.</p>
</section>
<section id="business-layer" class="level2">
<h2>4.2 Business Layer</h2>
<p>We will need a very simple business layer for our application. First of all, let’s have a look at our model entities:</p>
<figure>
<img src="images/thymeleafspring/stsm-model.png" alt="STSM model" /><figcaption>STSM model</figcaption>
</figure>
<p>A couple of very simple service classes will provide the required business methods. Like:</p>
<pre class="java"><code>@Service
public class SeedStarterService {
@Autowired
private SeedStarterRepository seedstarterRepository;
public List<SeedStarter> findAll() {
return this.seedstarterRepository.findAll();
}
public void add(final SeedStarter seedStarter) {
this.seedstarterRepository.add(seedStarter);
}
}</code></pre>
<p>And:</p>
<pre class="java"><code>@Service
public class VarietyService {
@Autowired
private VarietyRepository varietyRepository;
public List<Variety> findAll() {
return this.varietyRepository.findAll();
}
public Variety findById(final Integer id) {
return this.varietyRepository.findById(id);
}
}</code></pre>
</section>
<section id="spring-mvc-configuration" class="level2">
<h2>4.3 Spring MVC configuration</h2>
<p>Next we need to set up the Spring MVC configuration for the application, which will include not only the standard Spring MVC artifacts like resource handling or annotation scanning, but also the creation of the Template Engine and View Resolver instances.</p>
<pre class="java"><code>@Configuration
@EnableWebMvc
@ComponentScan
public class SpringWebConfig
extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
public SpringWebConfig() {
super();
}
public void setApplicationContext(final ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
/* ******************************************************************* */
/* GENERAL CONFIGURATION ARTIFACTS */
/* Static Resources, i18n Messages, Formatters (Conversion Service) */
/* ******************************************************************* */
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}
@Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatter(varietyFormatter());
registry.addFormatter(dateFormatter());
}
@Bean
public VarietyFormatter varietyFormatter() {
return new VarietyFormatter();
}
@Bean
public DateFormatter dateFormatter() {
return new DateFormatter();
}
/* **************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS */
/* TemplateResolver <- TemplateEngine <- ViewResolver */
/* **************************************************************** */
@Bean
public SpringResourceTemplateResolver templateResolver(){
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// Enabling the SpringEL compiler with Spring 4.2.4 or newer can
// speed up execution in most scenarios, but might be incompatible
// with specific cases when expressions in one template are reused
// across different data types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
}</code></pre>
</section>
<section id="the-controller" class="level2">
<h2>4.4 The Controller</h2>
<p>Of course, we will also need a controller for our application. As the STSM will only contain one web page with a list of seed starters and a form for adding new ones, we will write only one controller class for all the server interactions:</p>
<pre class="java"><code>@Controller
public class SeedStarterMngController {
@Autowired
private VarietyService varietyService;
@Autowired
private SeedStarterService seedStarterService;
...
}</code></pre>
<p>Now let’s see what we can add to this controller class.</p>
<section id="model-attributes" class="level3">
<h3>Model Attributes</h3>
<p>First we will add some model attributes that we will need in the page:</p>
<pre class="java"><code>@ModelAttribute("allTypes")
public List<Type> populateTypes() {
return Arrays.asList(Type.ALL);
}
@ModelAttribute("allFeatures")
public List<Feature> populateFeatures() {
return Arrays.asList(Feature.ALL);
}
@ModelAttribute("allVarieties")
public List<Variety> populateVarieties() {
return this.varietyService.findAll();
}
@ModelAttribute("allSeedStarters")
public List<SeedStarter> populateSeedStarters() {
return this.seedStarterService.findAll();
}</code></pre>
</section>
<section id="mapped-methods" class="level3">
<h3>Mapped methods</h3>
<p>And now the most important part of a controller, the mapped methods: one for showing the form page, and another one for processing the addition of new <code>SeedStarter</code> objects.</p>
<pre class="java"><code>@RequestMapping({"/","/seedstartermng"})
public String showSeedstarters(final SeedStarter seedStarter) {
seedStarter.setDatePlanted(Calendar.getInstance().getTime());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"save"})
public String saveSeedstarter(
final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "seedstartermng";
}
this.seedStarterService.add(seedStarter);
model.clear();
return "redirect:/seedstartermng";
}</code></pre>
</section>
</section>
<section id="configuring-a-conversion-service" class="level2">
<h2>4.5 Configuring a Conversion Service</h2>
<p>In order to allow easy formatting of <code>Date</code> and also <code>Variety</code> objects in our view layer, we configured our application so that a Spring <code>ConversionService</code> object was created and initialized (by the <code>WebMvcConfigurerAdapter</code> we extend) with a couple of <em>formatter</em> objects we will need. See it again:</p>
<pre class="java"><code>@Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatter(varietyFormatter());
registry.addFormatter(dateFormatter());
}
@Bean
public VarietyFormatter varietyFormatter() {
return new VarietyFormatter();
}
@Bean
public DateFormatter dateFormatter() {
return new DateFormatter();
}</code></pre>
<p>Spring <em>formatters</em> are implementations of the <code>org.springframework.format.Formatter</code> interface. For more information on how the Spring conversion infrastructure works, see the docs at <a href="http://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/html/validation.html#core-convert">spring.io</a>.</p>
<p>Let’s have a look at the <code>DateFormatter</code>, which formats dates according to a format string present at the <code>date.format</code> message key of our <code>Messages.properties</code>:</p>
<pre class="java"><code>public class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
}
}</code></pre>
<p>The <code>VarietyFormatter</code> automatically converts between our <code>Variety</code> entities and the way we want to use them in our forms (basically, by their <code>id</code> field values):</p>
<pre class="java"><code>public class VarietyFormatter implements Formatter<Variety> {
@Autowired
private VarietyService varietyService;
public VarietyFormatter() {
super();
}
public Variety parse(final String text, final Locale locale) throws ParseException {
final Integer varietyId = Integer.valueOf(text);
return this.varietyService.findById(varietyId);
}
public String print(final Variety object, final Locale locale) {
return (object != null ? object.getId().toString() : "");
}
}</code></pre>
<p>We will learn more on how these formatters affect the way our data is displayed later on.</p>
</section>
</section>
<section id="listing-seed-starter-data" class="level1">
<h1>5 Listing Seed Starter Data</h1>
<p>The first thing that our <code>/WEB-INF/templates/seedstartermng.html</code> page will show is a listing with the seed starters currently stored. For this we will need some externalized messages and also some expression evaluation on model attributes. Like this:</p>
<pre class="html"><code><div class="seedstarterlist" th:unless="${#lists.isEmpty(allSeedStarters)}">
<h2 th:text="#{title.list}">List of Seed Starters</h2>
<table>
<thead>
<tr>
<th th:text="#{seedstarter.datePlanted}">Date Planted</th>
<th th:text="#{seedstarter.covered}">Covered</th>
<th th:text="#{seedstarter.type}">Type</th>
<th th:text="#{seedstarter.features}">Features</th>
<th th:text="#{seedstarter.rows}">Rows</th>
</tr>
</thead>
<tbody>
<tr th:each="sb : ${allSeedStarters}">
<td th:text="${{sb.datePlanted}}">13/01/2011</td>
<td th:text="#{|bool.${sb.covered}|}">yes</td>
<td th:text="#{|seedstarter.type.${sb.type}|}">Wireframe</td>
<td th:text="${#strings.arrayJoin(
#messages.arrayMsg(
#strings.arrayPrepend(sb.features,'seedstarter.feature.')),
', ')}">Electric Heating, Turf</td>
<td>
<table>
<tbody>
<tr th:each="row,rowStat : ${sb.rows}">
<td th:text="${rowStat.count}">1</td>
<td th:text="${row.variety.name}">Thymus Thymi</td>
<td th:text="${row.seedsPerCell}">12</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div></code></pre>
<p>Lots to see here. Let’s have a look at each fragment separately.</p>
<p>First of all, this section will only be shown if there are any seed starters. We achieve that with a th:unless attribute and the <code>#lists.isEmpty(...)</code> function.</p>
<pre class="html"><code><div class="seedstarterlist" th:unless="${#lists.isEmpty(allSeedStarters)}"></code></pre>
<p>Note that all utility objects like <code>#lists</code> are available in Spring EL expressions just as they were in OGNL expressions in the Standard Dialect.</p>
<p>The next thing to see is a lot of internationalized (externalized) texts, like:</p>
<pre class="html"><code><h2 th:text="#{title.list}">List of Seed Starters</h2>
<table>
<thead>
<tr>
<th th:text="#{seedstarter.datePlanted}">Date Planted</th>
<th th:text="#{seedstarter.covered}">Covered</th>
<th th:text="#{seedstarter.type}">Type</th>
<th th:text="#{seedstarter.features}">Features</th>
<th th:text="#{seedstarter.rows}">Rows</th>
...</code></pre>
<p>This being a Spring MVC application, we already defined a <code>MessageSource</code> bean in our Spring configuration (<code>MessageSource</code> objects are the standard way of managing externalized texts in Spring MVC):</p>
<pre class="java"><code>@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}</code></pre>
<p>…and that <code>basename</code> property indicates that we will have files like <code>Messages_es.properties</code> or <code>Messages_en.properties</code> in our classpath. Let’s have a look at the Spanish version:</p>
<pre class="properties"><code>title.list=Lista de semilleros
date.format=dd/MM/yyyy
bool.true=sí
bool.false=no
seedstarter.datePlanted=Fecha de plantación
seedstarter.covered=Cubierto
seedstarter.type=Tipo
seedstarter.features=Características
seedstarter.rows=Filas
seedstarter.type.WOOD=Madera
seedstarter.type.PLASTIC=Plástico
seedstarter.feature.SEEDSTARTER_SPECIFIC_SUBSTRATE=Sustrato específico para semilleros
seedstarter.feature.FERTILIZER=Fertilizante
seedstarter.feature.PH_CORRECTOR=Corrector de PH</code></pre>
<p>In the first column of the table listing we will show the date when the seed starter was prepared. But <strong>we will show it formatted</strong> in the way we defined in our <code>DateFormatter</code>. In order to do that we will use the double-brace syntax (<code>${{...}}</code>), which will automatically apply the Spring Conversion Service, including the <code>DateFormatter</code> we registered at configuration.</p>
<pre class="html"><code><td th:text="${{sb.datePlanted}}">13/01/2011</td></code></pre>
<p>Next is showing whether the seed starter container is covered or not, by transforming the value of the boolean covered bean property into an internationalized <em>“yes”</em> or <em>“no”</em> with a literal substitution expression:</p>
<pre class="html"><code><td th:text="#{|bool.${sb.covered}|}">yes</td></code></pre>
<p>Now we have to show the type of seed starter container. Type is a java enum with two values (<code>WOOD</code> and <code>PLASTIC</code>), and that’s why we defined two properties in our <code>Messages</code> file called <code>seedstarter.type.WOOD</code> and <code>seedstarter.type.PLASTIC</code>.</p>
<p>But in order to obtain the internationalized names of the types, we will need to add the <code>seedstarter.type.</code> prefix to the enum value by means of an expression, which result we will then use as the message key:</p>
<pre class="html"><code><td th:text="#{|seedstarter.type.${sb.type}|}">Wireframe</td></code></pre>
<p>The most difficult part of this listing is the <em>features</em> column. In it we want to display all the features of our container —that come in the form of an array of <code>Feature</code> enums—, separated by commas. Like <em>“Electric Heating, Turf”</em>.</p>
<p>Note that this is particularly difficult because these enum values also need to be externalized, as we did with Types. The flow is then:</p>
<ol type="1">
<li>Prepend the corresponding prefix to all the elements of the <code>features</code> array.</li>
<li>Obtain the externalized messages corresponding to all the keys from step 1.</li>
<li>Join all the messages obtained in step 2, using a comma as a delimiter.</li>
</ol>
<p>For achieving this, we create the following code:</p>
<pre class="html"><code><td th:text="${#strings.arrayJoin(
#messages.arrayMsg(
#strings.arrayPrepend(sb.features,'seedstarter.feature.')),
', ')}">Electric Heating, Turf</td></code></pre>
<p>The last column of our listing will be quite simple, in fact. Even if it has a nested table for showing the contents of each row in the container:</p>
<pre class="html"><code><td>
<table>
<tbody>
<tr th:each="row,rowStat : ${sb.rows}">
<td th:text="${rowStat.count}">1</td>
<td th:text="${row.variety.name}">Thymus Thymi</td>
<td th:text="${row.seedsPerCell}">12</td>
</tr>
</tbody>
</table>
</td></code></pre>
</section>
<section id="creating-a-form" class="level1">
<h1>6 Creating a Form</h1>
<section id="handling-the-command-object" class="level2">
<h2>6.1 Handling the command object</h2>
<p><em>Command object</em> is the name Spring MVC gives to form-backing beans, this is, to objects that model a form’s fields and provide getter and setter methods that will be used by the framework for establishing and obtaining the values input by the user at the browser side.</p>
<p>Thymeleaf requires you to specify the command object by using a <code>th:object</code> attribute in your <code><form></code> tag:</p>
<pre class="html"><code><form action="#" th:action="@{/seedstartermng}" th:object="${seedStarter}" method="post">
...
</form></code></pre>
<p>This is consistent with other uses of <code>th:object,</code> but in fact this specific scenario adds some limitations in order to correctly integrate with Spring MVC’s infrastructure:</p>
<ul>
<li>Values for <code>th:object</code> attributes in form tags must be variable expressions (<code>${...}</code>) specifying only the name of a model attribute, without property navigation. This means that an expression like <code>${seedStarter}</code> is valid, but <code>${seedStarter.data}</code> would not be.</li>
<li>Once inside the <code><form></code> tag, no other <code>th:object</code> attribute can be specified. This is consistent with the fact that HTML forms cannot be nested.</li>
</ul>
</section>
<section id="inputs" class="level2">
<h2>6.2 Inputs</h2>
<p>Let’s see now how to add an input to our form:</p>
<pre class="html"><code><input type="text" th:field="*{datePlanted}" /></code></pre>
<p>As you can see, we are introducing a new attribute here: <code>th:field.</code> This is a very important feature for Spring MVC integration because it does all the heavy work of binding your input with a property in the form-backing bean. You can see it as an equivalent of the path attribute in a <form:input> tag from Spring MVC’s JSP tag library.</p>
<p>The <code>th:field</code> attribute behaves differently depending on whether it is attached to an <code><input></code>, <code><select></code> or <code><textarea></code> tag (and also depending on the specific type of <code><input></code> tag). In this case (<code>input[type=text]</code>), the above line of code is similar to:</p>
<pre class="html"><code><input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" /></code></pre>
<p>…but in fact it is a little bit more than that, because <code>th:field</code> will also apply the registered Spring Conversion Service, including the <code>DateFormatter</code> we saw before (even if the field expression is not double-bracketed). Thanks to this, the date will be shown correctly formatted.</p>
<p>Values for <code>th:field</code> attributes must be selection expressions (<code>*{...}</code>), which makes sense given the fact that they will be evaluated on the form-backing bean and not on the context variables (or model attributes in Spring MVC jargon).</p>
<p>Contrary to the ones in <code>th:object</code>, these expressions can include property navigation (in fact any expression allowed for the path attribute of a <code><form:input></code> JSP tag will be allowed here).</p>
<p>Note that <code>th:field</code> also understands the new types of <code><input></code> element introduced by HTML5 like <code><input type="datetime" ... /></code>, <code><input type="color" ... /></code>, etc., effectively adding complete HTML5 support to Spring MVC.</p>
</section>
<section id="checkbox-fields" class="level2">
<h2>6.3 Checkbox fields</h2>
<p><code>th:field</code> also allows us to define checkbox inputs. Let’s see an example from our HTML page:</p>
<pre class="html"><code><div>
<label th:for="${#ids.next('covered')}" th:text="#{seedstarter.covered}">Covered</label>
<input type="checkbox" th:field="*{covered}" />
</div></code></pre>
<p>Note there’s some fine stuff here besides the checkbox itself, like an externalized label and also the use of the <code>#ids.next('covered')</code> function for obtaining the value that will be applied to the id attribute of the checkbox input.</p>
<p>Why do we need this dynamic generation of an id attribute for this field? Because checkboxes are potentially multi-valued, and thus their id values will always be suffixed a sequence number (by internally using the <code>#ids.seq(...)</code> function) in order to ensure that each of the checkbox inputs for the same property has a different id value.</p>
<p>We can see this more easily if we look at such a multi-valued checkbox field:</p>
<pre class="html"><code><ul>
<li th:each="feat : ${allFeatures}">
<input type="checkbox" th:field="*{features}" th:value="${feat}" />
<label th:for="${#ids.prev('features')}"
th:text="#{${'seedstarter.feature.' + feat}}">Heating</label>
</li>
</ul></code></pre>
<p>Note that we’ve added a <code>th:value</code> attribute this time, because the features field is not a boolean like covered was, but instead is an array of values.</p>
<p>Let’s see the HTML output generated by this code:</p>
<pre class="html"><code><ul>
<li>
<input id="features1" name="features" type="checkbox" value="SEEDSTARTER_SPECIFIC_SUBSTRATE" />
<input name="_features" type="hidden" value="on" />
<label for="features1">Seed starter-specific substrate</label>
</li>
<li>
<input id="features2" name="features" type="checkbox" value="FERTILIZER" />
<input name="_features" type="hidden" value="on" />
<label for="features2">Fertilizer used</label>
</li>
<li>
<input id="features3" name="features" type="checkbox" value="PH_CORRECTOR" />
<input name="_features" type="hidden" value="on" />
<label for="features3">PH Corrector used</label>
</li>
</ul></code></pre>
<p>We can see here how a sequence suffix is added to each input’s id attribute, and how the <code>#ids.prev(...)</code> function allows us to retrieve the last sequence value generated for a specific input id.</p>
<blockquote>
<p>Don’t worry about those hidden inputs with <code>name="_features"</code>: they are automatically added in order to avoid problems with browsers not sending unchecked checkbox values to the server upon form submission.</p>
</blockquote>
<p>Also note that if our features property contained some selected values in our form-backing bean, <code>th:field</code>would have taken care of that and would have added a <code>checked="checked"</code> attribute to the corresponding input tags.</p>
</section>
<section id="radio-button-fields" class="level2">
<h2>6.4 Radio Button fields</h2>
<p>Radio button fields are specified in a similar way to non-boolean (multi-valued) checkboxes —except that they are not multivalued, of course:</p>
<pre class="html"><code><ul>
<li th:each="ty : ${allTypes}">
<input type="radio" th:field="*{type}" th:value="${ty}" />
<label th:for="${#ids.prev('type')}" th:text="#{${'seedstarter.type.' + ty}}">Wireframe</label>
</li>
</ul></code></pre>
</section>
<section id="dropdownlist-selectors" class="level2">
<h2>6.5 Dropdown/List selectors</h2>
<p>Select fields have two parts: the <code><select></code> tag and its nested <code><option></code> tags. When creating this kind of field, only the <code><select></code> tag has to include a <code>th:field</code> attribute, but the <code>th:value</code> attributes in the nested <code><option></code> tags will be very important because they will provide the means of knowing which is the currently selected option (in a similar way to non-boolean checkboxes and radio buttons).</p>
<p>Let’s re-build the type field as a dropdown select:</p>
<pre class="html"><code><select th:field="*{type}">
<option th:each="type : ${allTypes}"
th:value="${type}"
th:text="#{${'seedstarter.type.' + type}}">Wireframe</option>
</select></code></pre>
<p>At this point, understanding this piece of code is quite easy. Just notice how attribute precedence allows us to set the <code>th:each</code> attribute in the <code><option></code> tag itself.</p>
</section>
<section id="dynamic-fields" class="level2">
<h2>6.6 Dynamic fields</h2>
<p>Thanks to the advanced form-field binding capabilities in Spring MVC, we can use complex Spring EL expressions to bind dynamic form fields to our form-backing bean. This will allow us to create new Row objects in our <code>SeedStarter</code> bean, and to add those rows’ fields to our form at user request.</p>
<p>In order to do this, we will need a couple of new mapped methods in our controller, which will add or remove a row from our <code>SeedStarter</code> depending on the existence of specific request parameters:</p>
<pre class="java"><code>@RequestMapping(value="/seedstartermng", params={"addRow"})
public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return "seedstartermng";
}
@RequestMapping(value="/seedstartermng", params={"removeRow"})
public String removeRow(
final SeedStarter seedStarter, final BindingResult bindingResult,
final HttpServletRequest req) {
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
seedStarter.getRows().remove(rowId.intValue());
return "seedstartermng";
}</code></pre>
<p>And now we can add a dynamic table to our form:</p>
<pre class="html"><code><table>
<thead>
<tr>
<th th:text="#{seedstarter.rows.head.rownum}">Row</th>
<th th:text="#{seedstarter.rows.head.variety}">Variety</th>
<th th:text="#{seedstarter.rows.head.seedsPerCell}">Seeds per cell</th>
<th>
<button type="submit" name="addRow" th:text="#{seedstarter.row.add}">Add row</button>
</th>
</tr>
</thead>
<tbody>
<tr th:each="row,rowStat : *{rows}">
<td th:text="${rowStat.count}">1</td>
<td>
<select th:field="*{rows[__${rowStat.index}__].variety}">
<option th:each="var : ${allVarieties}"
th:value="${var.id}"
th:text="${var.name}">Thymus Thymi</option>
</select>
</td>
<td>
<input type="text" th:field="*{rows[__${rowStat.index}__].seedsPerCell}" />
</td>
<td>
<button type="submit" name="removeRow"
th:value="${rowStat.index}" th:text="#{seedstarter.row.remove}">Remove row</button>
</td>
</tr>
</tbody>
</table></code></pre>
<p>Quite a lot of things to see here, but not much we should not understand by now… except for one <code>strange</code> thing:</p>
<pre class="html"><code><select th:field="*{rows[__${rowStat.index}__].variety}">
...
</select></code></pre>
<p>If you recall from the <em>“Using Thymeleaf”</em> tutorial, that <code>__${...}__</code> syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression. But why that way of specifying the row index? Wouldn’t it be enough with:</p>
<pre class="html"><code><select th:field="*{rows[rowStat.index].variety}">
...
</select></code></pre>
<p>…well, actually, no. The problem is that Spring EL does not evaluate variables inside array index brackets, so when executing the above expression we would obtain an error telling us that <code>rows[rowStat.index]</code> (instead of <code>rows[0]</code>, <code>rows[1]</code>, etc) is not a valid position in the rows collection. That’s why preprocessing is needed here.</p>
<p>Let’s have a look at a fragment of the resulting HTML after pressing <em>“Add Row”</em> a couple of times:</p>
<pre class="html"><code><tbody>
<tr>
<td>1</td>
<td>
<select id="rows0.variety" name="rows[0].variety">
<option selected="selected" value="1">Thymus vulgaris</option>
<option value="2">Thymus x citriodorus</option>
<option value="3">Thymus herba-barona</option>
<option value="4">Thymus pseudolaginosus</option>
<option value="5">Thymus serpyllum</option>
</select>
</td>
<td>
<input id="rows0.seedsPerCell" name="rows[0].seedsPerCell" type="text" value="" />
</td>
<td>
<button name="removeRow" type="submit" value="0">Remove row</button>
</td>
</tr>
<tr>
<td>2</td>
<td>
<select id="rows1.variety" name="rows[1].variety">
<option selected="selected" value="1">Thymus vulgaris</option>
<option value="2">Thymus x citriodorus</option>
<option value="3">Thymus herba-barona</option>
<option value="4">Thymus pseudolaginosus</option>
<option value="5">Thymus serpyllum</option>
</select>
</td>
<td>
<input id="rows1.seedsPerCell" name="rows[1].seedsPerCell" type="text" value="" />
</td>
<td>
<button name="removeRow" type="submit" value="1">Remove row</button>
</td>
</tr>
</tbody></code></pre>
</section>
</section>
<section id="validation-and-error-messages" class="level1">
<h1>7 Validation and Error Messages</h1>
<p>Most of our forms will need to show validation messages in order to inform the user of the errors he/she has made.</p>
<p>Thymeleaf offers some tools for this: a couple of functions in the <code>#fields</code> object, the <code>th:errors</code> and the <code>th:errorclass</code> attributes.</p>
<section id="field-errors" class="level2">
<h2>7.1 Field errors</h2>
<p>Let’s see how we could set a specific CSS class to a field if it has an error:</p>
<pre class="html"><code><input type="text" th:field="*{datePlanted}"
th:class="${#fields.hasErrors('datePlanted')}? fieldError" /></code></pre>
<p>As you can see, the <code>#fields.hasErrors(...)</code> function receives the field expression as a parameter (<code>datePlanted</code>), and returns a boolean telling whether any validation errors exist for that field.</p>
<p>We could also obtain all the errors for that field and iterate them:</p>
<pre class="html"><code><ul>
<li th:each="err : ${#fields.errors('datePlanted')}" th:text="${err}" />
</ul></code></pre>
<p>Instead of iterating, we could have also used <code>th:errors</code>, a specialized attribute which builds a list with all the errors for the specified selector, separated by <code><br /></code>:</p>
<pre class="html"><code><input type="text" th:field="*{datePlanted}" />
<p th:if="${#fields.hasErrors('datePlanted')}" th:errors="*{datePlanted}">Incorrect date</p></code></pre>
<section id="simplifying-error-based-css-styling-therrorclass" class="level3">
<h3>Simplifying error-based CSS styling: <code>th:errorclass</code></h3>
<p>The example we saw above, <em>setting a CSS class to a form input if that field has errors</em>, is so common that Thymeleaf offers a specific attribute for doing exacly that: <code>th:errorclass</code>.</p>
<p>Applied to a form field tag (input, select, textarea…), it will read the name of the field to be examined from any existing <code>name</code> or <code>th:field</code> attributes in the same tag, and then append the specified CSS class to the tag if such field has any associated errors:</p>
<pre class="html"><code><input type="text" th:field="*{datePlanted}" class="small" th:errorclass="fieldError" /></code></pre>
<p>If <code>datePlanted</code> has errors, this will render as:</p>
<pre class="html"><code><input type="text" id="datePlanted" name="datePlanted" value="2013-01-01" class="small fieldError" /></code></pre>
</section>
</section>
<section id="all-errors" class="level2">
<h2>7.2 All errors</h2>
<p>And what if we want to show all the errors in the form? We just need to query the <code>#fields.hasErrors(...)</code> and <code>#fields.errors(...)</code> methods with the <code>'*'</code> or <code>'all'</code> constants (which are equivalent):</p>
<pre class="html"><code><ul th:if="${#fields.hasErrors('*')}">
<li th:each="err : ${#fields.errors('*')}" th:text="${err}">Input is incorrect</li>
</ul></code></pre>
<p>As in the examples above, we could obtain all the errors and iterate them…</p>
<pre class="html"><code><ul>
<li th:each="err : ${#fields.errors('*')}" th:text="${err}" />
</ul></code></pre>
<p>…as well as build a <code><br /></code>-separated list:</p>
<pre class="html"><code><p th:if="${#fields.hasErrors('all')}" th:errors="*{all}">Incorrect date</p></code></pre>
<p>Finally note that <code>#fields.hasErrors('*')</code> is equivalent to <code>#fields.hasAnyErrors()</code> and <code>#fields.errors('*')</code> is equivalent to <code>#fields.allErrors()</code>. Use whichever syntax you prefer:</p>
<pre class="html"><code><div th:if="${#fields.hasAnyErrors()}">
<p th:each="err : ${#fields.allErrors()}" th:text="${err}">...</p>
</div></code></pre>
</section>
<section id="global-errors" class="level2">
<h2>7.3 Global errors</h2>
<p>There is a third type of error in a Spring form: <em>global</em> errors. These are errors that are not associated with any specific fields in the form, but still exist.</p>
<p>Thymeleaf offers the <code>global</code> constant for accessing these errors:</p>
<pre class="html"><code><ul th:if="${#fields.hasErrors('global')}">
<li th:each="err : ${#fields.errors('global')}" th:text="${err}">Input is incorrect</li>
</ul></code></pre>
<pre class="html"><code><p th:if="${#fields.hasErrors('global')}" th:errors="*{global}">Incorrect date</p></code></pre>
<p>…as well as equivalent <code>#fields.hasGlobalErrors()</code> and <code>#fields.globalErrors()</code> convenience methods:</p>
<pre class="html"><code><div th:if="${#fields.hasGlobalErrors()}">
<p th:each="err : ${#fields.globalErrors()}" th:text="${err}">...</p>
</div></code></pre>
</section>
<section id="displaying-errors-outside-forms" class="level2">
<h2>7.4 Displaying errors outside forms</h2>
<p>Form validation errors can also be displayed outside forms by using variable (<code>${...}</code>) instead of selection (<code>*{...}</code>) expressions and prefixing the name of the form-backing bean:</p>
<pre class="html"><code><div th:errors="${myForm}">...</div>
<div th:errors="${myForm.date}">...</div>
<div th:errors="${myForm.*}">...</div>
<div th:if="${#fields.hasErrors('${myForm}')}">...</div>
<div th:if="${#fields.hasErrors('${myForm.date}')}">...</div>
<div th:if="${#fields.hasErrors('${myForm.*}')}">...</div>
<form th:object="${myForm}">
...
</form></code></pre>
</section>
<section id="rich-error-objects" class="level2">
<h2>7.5 Rich error objects</h2>
<p>Thymeleaf offers the possibility to obtain form error information in the form of beans (instead of mere <em>strings</em>), with the <code>fieldName</code> (String), <code>message</code> (String) and <code>global</code> (boolean) attributes.</p>
<p>These errors can be obtained by means of the <code>#fields.detailedErrors()</code> utility method:</p>
<pre class="html"><code><ul>
<li th:each="e : ${#fields.detailedErrors()}" th:class="${e.global}? globalerr : fielderr">
<span th:text="${e.global}? '*' : ${e.fieldName}">The field name</span> |
<span th:text="${e.message}">The error message</span>
</li>
</ul></code></pre>
</section>
</section>
<section id="its-still-a-prototype" class="level1">
<h1>8 It’s still a Prototype!</h1>
<p>Our application is ready now. But let’s have a second look at the <code>.html</code> page we created…</p>
<p>One of the nicest consequences of working with Thymeleaf is that after all this functionality we have added to our HTML, we can still use it as a prototype (we say it is a <em>Natural Template</em>). Let’s open <code>seedstartermng.html</code> directly in our browser without executing our application:</p>
<figure>
<img src="images/thymeleafspring/stsm-natural-templating.png" alt="STSM natural templating" /><figcaption>STSM natural templating</figcaption>
</figure>
<p>There it is! It’s not a working application, it’s not real data… but it is a perfectly valid prototype made up of perfectly displayable HTML code.</p>
</section>
<section id="the-conversion-service" class="level1">
<h1>9 The Conversion Service</h1>
<section id="configuration" class="level2">
<h2>9.1 Configuration</h2>
<p>As explained before, Thymeleaf can make use of a Conversion Service registered at the Application Context. Our application configuration class, by extending Spring’s own <code>WebMvcConfigurerAdapter</code> helper, will automatically register such conversion service, which we can configure by adding the <em>formatters</em> that we need. Let’s see again what it looks like:</p>
<pre class="java"><code>@Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatter(varietyFormatter());
registry.addFormatter(dateFormatter());
}
@Bean
public VarietyFormatter varietyFormatter() {
return new VarietyFormatter();
}
@Bean
public DateFormatter dateFormatter() {
return new DateFormatter();