forked from seam2/jboss-seam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTutorial.xml
executable file
·3367 lines (2869 loc) · 159 KB
/
Tutorial.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN" "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
<chapter id="tutorial">
<title>Seam Tutorial</title>
<section id="try-examples">
<title>Using the Seam examples</title>
<para>Seam provides a number of example applications demonstrating how to use the various features
of Seam. This tutorial will guide you through a few of those examples to help you get started
learning Seam. The Seam examples are located in the <filename>examples</filename> subdirectory
of the Seam distribution. The registration example, which will be the first example we look at,
is in the <filename>examples/registration</filename> directory.</para>
<para>Each example has the very similar directory structure which is based on <ulink url="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html">
Maven project structure defaults</ulink>:</para>
<itemizedlist>
<listitem>
<para> The <filename><example>-ear</filename> directory contains enterprise application submodule files such as
aggregator for web application files, EJB project.
</para>
</listitem>
<listitem>
<para> The <filename><example>-web</filename> directory contains web application submodule view-related files such as
web page templates, images and stylesheets.
</para>
</listitem>
<listitem>
<para> The <filename><example>-ejb</filename> directory contains Enterprise Java Beans components.
</para>
</listitem>
<listitem>
<para> The <filename><example>-tests</filename> directory contains integration and functional tests.
</para>
</listitem>
</itemizedlist>
<itemizedlist>
<listitem>
<para> The <filename><example>-web/src/main/webapp</filename> directory contains view-related files such as
web page templates, images and stylesheets.
</para>
</listitem>
<listitem>
<para> The <filename><example>-[ear|ejb]/src/main/resources</filename> directory contains deployment descriptors and
other configuration files.
</para>
</listitem>
<listitem>
<para> The <filename><example>-ejb/src/main/java</filename> directory contains the application source code. </para>
</listitem>
</itemizedlist>
<para>
The example applications run on JBoss AS 7.1.1 with no additional configuration.
The following sections will explain the procedure. Note that all the examples
are built and run from the Maven <filename>pom.xml</filename>, so you'll need at least version 3.x
of Maven installed before you get started. At the time of writing this text recent version of Maven was 3.0.4.
</para>
<section>
<title>Running the examples on JBoss AS</title>
<para>The examples are configured for use on JBoss AS 7.1. You'll need to set <literal>JBOSS_HOME</literal>,
in your environment, to the location of your JBoss AS installation.</para>
<para>Once you've set the location of JBoss AS and started the application server, you can build
any example by typing <literal>mvn install</literal> in the example root directory. Any example is deployed by changing directory
to *-ear or *-web directory in case of existence only *-web submodule. Type in that submodule <literal>mvn jboss-as:deploy</literal>.
Any example that is packaged as an EAR deploys to a URL like
<literal>/seam-<replaceable>example</replaceable></literal>, where <replaceable>example</replaceable> is
the name of the example folder, with one exception. If the example folder begins with seam, the prefix
"seam" is ommitted. For instance, if JBoss AS is running on port 8080, the URL for the registration
example is <ulink url="http://localhost:8080/seam-registration/">
<literal>http://localhost:8080/seam-registration/</literal></ulink>, whereas the URL for the seamspace
example is <ulink url="http://localhost:8080/seam-space/">
<literal>http://localhost:8080/seam-space/</literal></ulink>.</para>
<para>If, on the other hand, the example gets packaged as a WAR, then it deploys to a URL like
<literal>/jboss-seam-<replaceable>example</replaceable></literal>. Several of the examples
can only be deployed as a WAR. Those examples are groovybooking, hibernate, jpa, and spring.
</para>
</section>
<section>
<title>Running the example tests</title>
<para>
Most of the examples come with a suite of Arquillian JUnit integration tests. The easiest way to run the tests is
to run <literal>mvn verify -Darquillian=jbossas-managed-7</literal>. It is also possible to run the tests inside your IDE using the
JUnit plugin. Consult the readme.txt in the examples directory of the Seam distribution for more
information.
</para>
</section>
</section>
<section id="registration-example">
<title>Your first Seam application: the registration example</title>
<para> The registration example is a simple application that lets a new user store his username, real
name and password in the database. The example isn't intended to show off all of the cool functionality of
Seam. However, it demonstrates the use of an EJB3 session bean as a JSF action listener, and basic
configuration of Seam. </para>
<para> We'll go slowly, since we realize you might not yet be familiar with EJB 3.0. </para>
<para> The start page displays a very basic form with three input fields. Try filling them in and then
submitting the form. This will save a user object in the database. </para>
<mediaobject>
<imageobject role="fo">
<imagedata fileref="images/registration.png" align="center" scalefit="1"/>
</imageobject>
<imageobject role="html">
<imagedata fileref="images/registration.png" align="center"/>
</imageobject>
</mediaobject>
<section>
<title>Understanding the code</title>
<para> The example is implemented with two Facelets templates, one entity bean and one
stateless session bean. Let's take a look at the code, starting from the "bottom".
</para>
<section>
<title>The entity bean: <literal>User.java</literal></title>
<para> We need an JPA entity bean for user data. This class defines <emphasis>persistence</emphasis> and
<emphasis>validation</emphasis> declaratively, via annotations. It also needs some extra
annotations that define the class as a Seam component. </para>
<!-- Can't use code hightlighting with callouts -->
<example>
<title>User.java</title>
<programlistingco>
<areaspec>
<area id="registration-entity-annotation" coords="1"/>
<area id="registration-name-annotation" coords="2"/>
<area id="registration-scope-annotation" coords="3"/>
<area id="registration-table-annotation" coords="4"/>
<area id="registration-attributes" coords="9"/>
<area id="registration-empty-constructor" coords="20"/>
<area id="registration-notnull" coords="22"/>
<area id="registration-id-annotation" coords="44"/>
</areaspec>
<programlisting role="JAVA"><![CDATA[@Entity
@Name("user")
@Scope(SESSION)
@Table(name="users")
public class User implements Serializable
{
private static final long serialVersionUID = 1881413500711441951L;
private String username;
private String password;
private String name;
public User(String name, String password, String username)
{
this.name = name;
this.password = password;
this.username = username;
}
public User() {}
@NotNull @Size(min=5, max=15)
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
@NotNull
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Id @NotNull @Size(min=5, max=15)
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}]]></programlisting>
<calloutlist>
<callout arearefs="registration-entity-annotation">
<para> The JPA standard <literal>@Entity</literal> annotation indicates that the
<literal>User</literal> class is an entity bean. </para>
</callout>
<callout arearefs="registration-name-annotation">
<para> A Seam component needs a <emphasis>component name</emphasis> specified by the
<link linkend="name-annotation">
<literal>@Name</literal>
</link> annotation. This name must be unique within the Seam application. When JSF
asks Seam to resolve a context variable with a name that is the same as a Seam
component name, and the context variable is currently undefined (null), Seam will
instantiate that component, and bind the new instance to the context variable. In
this case, Seam will instantiate a <literal>User</literal> the first time JSF
encounters a variable named <literal>user</literal>. </para>
</callout>
<callout arearefs="registration-scope-annotation">
<para> Whenever Seam instantiates a component, it binds the new instance to a context
variable in the component's <emphasis>default context</emphasis>. The default
context is specified using the <link linkend="scope-annotation">
<literal>@Scope</literal>
</link> annotation. The <literal>User</literal> bean is a session scoped component.
</para>
</callout>
<callout arearefs="registration-table-annotation">
<para> The JPA standard <literal>@Table</literal> annotation indicates that the
<literal>User</literal> class is mapped to the <literal>users</literal> table.
</para>
</callout>
<callout arearefs="registration-attributes">
<para>
<literal>name</literal>, <literal>password</literal> and <literal>username</literal>
are the persistent attributes of the entity bean. All of our persistent attributes
define accessor methods. These are needed when this component is used by JSF in the
render response and update model values phases. </para>
</callout>
<callout arearefs="registration-empty-constructor">
<para> An empty constructor is both required by both the JPA specification and by Seam.
</para>
</callout>
<callout arearefs="registration-notnull">
<para> The <literal>@NotNull</literal> and <literal>@Size</literal> annotations are
part of the Bean Validation annotations specification (JSR-303). Seam integrates
Bean Validation through Hibernate Validator, which is the reference implementation,
and lets you use it for data validation (even if you are not using Hibernate for
persistence). </para>
</callout>
<callout arearefs="registration-id-annotation">
<para> The JPA standard <literal>@Id</literal> annotation indicates the primary key
attribute of the entity bean. </para>
</callout>
</calloutlist>
</programlistingco>
</example>
<para> The most important things to notice in this example are the <literal>@Name</literal> and
<literal>@Scope</literal> annotations. These annotations establish that this class is a Seam component. </para>
<para> We'll see below that the properties of our <literal>User</literal> class are bound
directly to JSF components and are populated by JSF during the update model values phase. We
don't need any tedious glue code to copy data back and forth between the JSF pages and the
entity bean domain model. </para>
<para> However, entity beans shouldn't do transaction management or database access. So we can't use
this component as a JSF action listener. For that we need a session bean. </para>
</section>
<section>
<title>The stateless session bean class: <literal>RegisterAction.java</literal></title>
<para> Most Seam application use session beans as JSF action listeners (you can use JavaBeans instead if
you like). </para>
<para> We have exactly one JSF action in our application, and one session bean method attached to it. In
this case, we'll use a stateless session bean, since all the state associated with our action is
held by the <literal>User</literal> bean. </para>
<para> This is the only really interesting code in the example! </para>
<!-- Can't use code hightlighting with callouts -->
<example>
<title>RegisterAction.java</title>
<programlistingco>
<areaspec>
<area id="registration-stateless-annotation" coords="1"/>
<area id="registration-in-annotation" coords="6"/>
<area id="registration-persistencecontext-annotation" coords="9"/>
<area id="registration-logger-annotation" coords="12"/>
<area id="registration-action-listener" coords="15"/>
<area id="registration-query" coords="18"/>
<area id="registration-log" coords="24"/>
<area id="registration-outcome" coords="25"/>
<area id="registration-builtin" coords="29"/>
</areaspec>
<programlisting role="JAVA"><![CDATA[@Stateless
@Name("register")
public class RegisterAction implements Register
{
@In
private User user;
@PersistenceContext
private EntityManager em;
@Logger
private Log log;
public String register()
{
List existing = em.createQuery(
"select username from User where username = #{user.username}")
.getResultList();
if (existing.size()==0)
{
em.persist(user);
log.info("Registered new user #{user.username}");
return "/registered.xhtml";
}
else
{
FacesMessages.instance().add("User #{user.username} already exists");
return null;
}
}
}]]></programlisting>
<calloutlist>
<callout arearefs="registration-stateless-annotation">
<para> The EJB <literal>@Stateless</literal> annotation marks this class as
a stateless session bean. </para>
</callout>
<callout arearefs="registration-in-annotation">
<para> The <link linkend="in-annotation">
<literal>@In</literal>
</link> annotation marks an attribute of the bean as injected by Seam. In this case,
the attribute is injected from a context variable named <literal>user</literal> (the
instance variable name). </para>
</callout>
<callout arearefs="registration-persistencecontext-annotation">
<para> The EJB standard <literal>@PersistenceContext</literal> annotation is used to
inject the JPA entity manager. </para>
</callout>
<callout arearefs="registration-logger-annotation">
<para> The Seam <literal>@Logger</literal> annotation is used to inject the component's
<literal>Log</literal> instance. </para>
</callout>
<callout arearefs="registration-action-listener">
<para> The action listener method uses the standard JPA
<literal>EntityManager</literal> API to interact with the database, and returns the
JSF outcome. Note that, since this is a session bean, a transaction is automatically
begun when the <literal>register()</literal> method is called, and committed when it
completes. </para>
</callout>
<callout arearefs="registration-query">
<para> Notice that Seam lets you use a JSF EL expression inside JPQL. Under the
covers, this results in an ordinary JPA <literal>setParameter()</literal> call on
the standard JPA <literal>Query</literal> object. Nice, huh? </para>
</callout>
<callout arearefs="registration-log">
<para> The <literal>Log</literal> API lets us easily display templated log messages which
can also make use of JSF EL expressions.
</para>
</callout>
<callout arearefs="registration-outcome">
<para> JSF action listener methods return a string-valued outcome that determines what
page will be displayed next. A null outcome (or a void action listener method)
redisplays the previous page. In plain JSF, it is normal to always use a JSF
<emphasis>navigation rule</emphasis> to determine the JSF view id from the
outcome. For complex application this indirection is useful and a good practice.
However, for very simple examples like this one, Seam lets you use the JSF view id
as the outcome, eliminating the requirement for a navigation rule. <emphasis>Note
that when you use a view id as an outcome, Seam always performs a browser
redirect.</emphasis>
</para>
</callout>
<callout arearefs="registration-builtin">
<para> Seam provides a number of <emphasis>built-in components</emphasis> to help solve
common problems. The <literal>FacesMessages</literal> component makes it easy to
display templated error or success messages. (As of Seam 2.1, you can use
<literal>StatusMessages</literal> instead to remove the semantic dependency on JSF).
Built-in Seam components may be obtained by injection, or by calling the
<literal>instance()</literal> method on the class of the built-in component.
</para>
</callout>
</calloutlist>
</programlistingco>
</example>
<para> Note that we did not explicitly specify a <literal>@Scope</literal> this time. Each Seam
component type has a default scope if not explicitly specified. For stateless session beans, the
default scope is the stateless context, which is the only sensible value.</para>
<para> Our session bean action listener performs the business and persistence logic for our
mini-application. In more complex applications, we might need require a separate service
layer. This is easy to achieve with Seam, but it's overkill for most web applications.
Seam does not force you into any particular strategy for application layering, allowing
your application to be as simple, or as complex, as you want.
</para>
<para>Note that in this simple
application, we've actually made it far more complex than it needs to be. If we had
used the Seam application framework controllers, we would have eliminated all of our
application code. However, then we wouldn't have had much of an application to explain.
</para>
</section>
<section>
<title>The session bean local interface: <literal>Register.java</literal></title>
<para>Naturally, our session bean needs a local interface.</para>
<example><title>Register.java</title>
<programlisting role="JAVA"><![CDATA[@Local
public interface Register
{
public String register();
}]]></programlisting></example>
<para> That's the end of the Java code. Now we'll look at the view.</para>
</section>
<section>
<title>The view: <literal>register.xhtml</literal> and <literal>registered.xhtml</literal></title>
<para> The view pages for a Seam application could be implemented using any technology that supports
JSF. In this example we use Facelets, because we think it's better than JSF.</para>
<example>
<title>register.xhtml</title>
<programlisting role="XHTML"><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.org/schema/seam/taglib"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Register New User</title>
</h:head>
<h:body>
<h:head>f:view>
<h:form>
<s:validateAll>
<h:panelGrid columns="2">
Username: <h:inputText value="#{user.username}" required="true"/>
Real Name: <h:inputText value="#{user.name}" required="true"/>
Password: <h:inputSecret value="#{user.password}" required="true"/>
</h:panelGrid>
</s:validateAll>
<h:messages/>
<h:commandButton value="Register" action="#{register.register}"/>
</h:form>
</f:view>
</h:body>
</html>]]></programlisting></example>
<para> The only thing here that is specific to Seam is the
<literal><s:validateAll></literal> tag. This JSF component tells JSF to validate all
the contained input fields against the Bean Validation annotations specified on the entity bean. </para>
<example>
<title>registered.xhtml</title>
<programlisting role="XHTML"><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Successfully Registered New User</title>
</h:head>
<h:body>
<f:view>
Welcome, #{user.name}, you are successfully registered as #{user.username}.
</f:view>
</h:body>
</html>
]]></programlisting>
</example>
<para> This is a simple Facelets page using some inline EL. There's nothing specific to Seam here. </para>
</section>
<section>
<title>The Seam component deployment descriptor: <literal>components.xml</literal></title>
<para>Since this is the first Seam app we've seen, we'll take a look at the deployment
descriptors. Before we get into them, it is worth noting that Seam strongly values
minimal configuration. These configuration files will be created for you when you create a Seam
application. You'll never need to touch most of these files. We're presenting them
now only to help you understand what all the pieces in the example are doing.
</para>
<para> If you've used many Java frameworks before, you'll be used to having to declare all your
component classes in some kind of XML file that gradually grows more and more unmanageable as your
project matures. You'll be relieved to know that Seam does not require that application components
be accompanied by XML. Most Seam applications require a very small amount of XML that does not grow
very much as the project gets bigger. </para>
<para> Nevertheless, it is often useful to be able to provide for <emphasis>some</emphasis> external
configuration of <emphasis>some</emphasis> components (particularly the components built in to
Seam). You have a couple of options here, but the most flexible option is to provide this
configuration in a file called <literal>components.xml</literal>, located in the
<literal>WEB-INF</literal> directory. We'll use the <literal>components.xml</literal> file to tell
Seam how to find our EJB components in JNDI: </para>
<example>
<title>components.xml</title>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.org/schema/seam/components"
xmlns:core="http://jboss.org/schema/seam/core"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/seam/core
http://jboss.org/schema/seam/core-2.3.xsd
http://jboss.org/schema/seam/components
http://jboss.org/schema/seam/components-2.3.xsd">
<core:init jndi-pattern="${jndiPattern}"/>
</components>]]></programlisting></example>
<para> This code configures a property named <literal>jndiPattern</literal> of a built-in Seam component
named <literal>org.jboss.seam.core.init</literal>. The funny <literal>@</literal> symbols are
there because our Maven build puts the correct JNDI pattern in when we deploy the application,
which it reads from the components.properties file. You learn more about how this process works in
<xref linkend="xml.descriptor"/>.</para>
<note>
<para>Eclipse M2e Web tools plugin can't use the <literal>@</literal> for token property filtering. Fortunately
there works the other way which is in Maven filtering defined - <literal>${property}</literal>.</para>
</note>
</section>
<section>
<title>The web deployment description: <literal>web.xml</literal></title>
<para> The presentation layer for our mini-application will be deployed in a WAR. So we'll need a web
deployment descriptor. </para>
<example>
<title>web.xml</title>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.seam</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>]]></programlisting></example>
<para> This <literal>web.xml</literal> file configures Seam and JSF. The configuration you see here is
pretty much identical in all Seam applications. </para>
</section>
<section>
<title>The JSF configuration: <literal>faces-config.xml</literal></title>
<para> Most Seam applications use JSF views as the presentation layer. So usually we'll need
<literal>faces-config.xml</literal>. In our case, we are going to use Facelets for
defining our views, so we need to tell JSF to use Facelets as its templating engine. </para>
<example>
<title>faces-config.xml</title>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">
</faces-config>]]></programlisting>
</example>
<para> Note that we don't need
any JSF managed bean declarations and neither FaceletViewHandler definition as Facelets are default view technology
in JSF 2! Our managed beans are annotated Seam components. So basically we don't need <filename>faces-config.xml</filename> at all,
but here is the <filename>faces-config.xml</filename> as the template for advanced JSF configurations.</para>
<para> In fact, once you have all the basic descriptors set up, the <emphasis>only</emphasis> XML you
need to write as you add new functionality to a Seam application is orchestration: navigation rules
or jBPM process definitions. Seam's stand is that <emphasis>process flow</emphasis> and
<emphasis>configuration data</emphasis> are the only things that truly belong in XML. </para>
<para> In this simple example, we don't even need a navigation rule, since we decided to embed the view
id in our action code. </para>
</section>
<section>
<title>The EJB deployment descriptor: <literal>ejb-jar.xml</literal></title>
<para> The <literal>ejb-jar.xml</literal> file integrates Seam with EJB3, by attaching the
<literal>SeamInterceptor</literal> to all session beans in the archive. </para>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<interceptors>
<interceptor>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>]]></programlisting>
</section>
<section>
<title>The JPA persistence deployment descriptor: <literal>persistence.xml</literal></title>
<para> The <literal>persistence.xml</literal> file tells the JPA persistence provider where to find the
datasource, and contains some vendor-specific settings. In this case, enables automatic schema
export at startup time. </para>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="userDatabase">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>]]></programlisting>
</section>
<section>
<title>The EAR deployment descriptor: <literal>application.xml</literal></title>
<para> Finally, since our application is deployed as an EAR, we need a deployment descriptor there, too. </para>
<note>
<para>This file can be generated by Maven EAR plugin and registration application has got this set up in registration-ear/pom.xml.</para>
</note>
<para>Just for clarity, the following is the result of that generation:</para>
<example id="registration-application-xml"><title>registration application</title>
<programlisting role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/application_6.xsd"
version="6">
<display-name>registration-ear</display-name>
<module>
<web>
<web-uri>registration-web.war</web-uri>
<context-root>/seam-registration</context-root>
</web>
</module>
<module>
<ejb>registration-ejb.jar</ejb>
</module>
<module>
<ejb>jboss-seam.jar</ejb>
</module>
</application>]]></programlisting>
</example>
<para> This deployment descriptor links modules in the enterprise archive and binds the web application
to the context root <literal>/seam-registration</literal>. </para>
<para> We've now seen <emphasis>all</emphasis> the files in the entire application! </para>
</section>
</section>
<section>
<title>How it works</title>
<para> When the form is submitted, JSF asks Seam to resolve the variable named <literal>user</literal>.
Since there is no value already bound to that name (in any Seam context), Seam instantiates the
<literal>user</literal> component, and returns the resulting <literal>User</literal> entity bean
instance to JSF after storing it in the Seam session context. </para>
<para> The form input values are now validated against the Bean Validator constraints specified on the
<literal>User</literal> entity. If the constraints are violated, JSF redisplays the page. Otherwise,
JSF binds the form input values to properties of the <literal>User</literal> entity bean. </para>
<para> Next, JSF asks Seam to resolve the variable named <literal>register</literal>. Seam uses the JNDI
pattern mentioned earlier to locate the stateless session bean, wraps it as a Seam component, and
returns it. Seam then presents this component to JSF and JSF invokes the <literal>register()</literal>
action listener method.</para>
<para> But Seam is not done yet. Seam intercepts the method call and injects the <literal>User</literal>
entity from the Seam session context, before allowing the invocation to continue. </para>
<para> The <literal>register()</literal> method checks if a user with the entered username already exists.
If so, an error message is queued with the <literal>FacesMessages</literal> component, and a null
outcome is returned, causing a page redisplay. The <literal>FacesMessages</literal> component
interpolates the JSF expression embedded in the message string and adds a JSF
<literal>FacesMessage</literal> to the view. </para>
<para> If no user with that username exists, the <literal>"/registered.xhtml"</literal> outcome triggers a
browser redirect to the <literal>registered.xhtml</literal> page. When JSF comes to render the page, it
asks Seam to resolve the variable named <literal>user</literal> and uses property values of the returned
<literal>User</literal> entity from Seam's session scope. </para>
</section>
</section>
<section id="messages">
<title>Clickable lists in Seam: the messages example</title>
<para> Clickable lists of database search results are such an important part of any online application that Seam
provides special functionality on top of JSF to make it easier to query data using JPQL or HQL and display
it as a clickable list using a JSF <literal><h:dataTable></literal>. The messages example
demonstrates this functionality. </para>
<mediaobject>
<imageobject role="fo">
<imagedata fileref="images/messages.png" align="center" scalefit="1"/>
</imageobject>
<imageobject role="html">
<imagedata fileref="images/messages.png" align="center"/>
</imageobject>
</mediaobject>
<section>
<title>Understanding the code</title>
<para> The message list example has one entity bean, <literal>Message</literal>, one session bean,
<literal>MessageListBean</literal> and one JSF. </para>
<section>
<title>The entity bean: <literal>Message.java</literal></title>
<para> The <literal>Message</literal> entity defines the title, text, date and time of a message, and a
flag indicating whether the message has been read: </para>
<example>
<title>Message.java</title>
<programlisting role="JAVA"><![CDATA[@Entity
@Name("message")
@Scope(EVENT)
public class Message implements Serializable
{
private Long id;
private String title;
private String text;
private boolean read;
private Date datetime;
@Id @GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
@NotNull @Size(max=100)
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
@NotNull @Lob
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
@NotNull
public boolean isRead()
{
return read;
}
public void setRead(boolean read)
{
this.read = read;
}
@NotNull
@Basic @Temporal(TemporalType.TIMESTAMP)
public Date getDatetime()
{
return datetime;
}
public void setDatetime(Date datetime)
{
this.datetime = datetime;
}
}]]></programlisting>
</example>
</section>
<section>
<title>The stateful session bean: <literal>MessageManagerBean.java</literal></title>
<para> Just like in the previous example, we have a session bean, <literal>MessageManagerBean</literal>,
which defines the action listener methods for the two buttons on our form. One of the buttons
selects a message from the list, and displays that message. The other button deletes a message. So
far, this is not so different to the previous example. </para>
<para> But <literal>MessageManagerBean</literal> is also responsible for fetching the list of messages
the first time we navigate to the message list page. There are various ways the user could navigate
to the page, and not all of them are preceded by a JSF action — the user might have
bookmarked the page, for example. So the job of fetching the message list takes place in a Seam
<emphasis>factory method</emphasis>, instead of in an action listener method. </para>
<para> We want to cache the list of messages in memory between server requests, so we will make this a
stateful session bean. </para>
<!-- Can't use code hightlighting with callouts -->
<example>
<title>MessageManagerBean.java</title>
<programlistingco>
<areaspec>
<area id="messages-datamodel" coords="7"/>
<area id="messages-datamodelselection" coords="10"/>
<area id="messages-out" coords="11"/>
<area id="messages-persistencecontext" coords="14"/>
<area id="messages-factory" coords="17"/>
<area id="messages-select" coords="24"/>
<area id="messages-delete" coords="29"/>
<area id="messages-remove" coords="36"/>
</areaspec>
<programlisting role="JAVA"><![CDATA[@Stateful
@Scope(SESSION)
@Name("messageManager")
public class MessageManagerBean implements Serializable, MessageManager
{
@DataModel
private List<Message> messageList;
@DataModelSelection
@Out(required=false)
private Message message;
@PersistenceContext(type=EXTENDED)
private EntityManager em;
@Factory("messageList")
public void findMessages()
{
messageList = em.createQuery("select msg from Message msg order by msg.datetime desc")
.getResultList();
}
public void select()
{
message.setRead(true);
}
public void delete()
{
messageList.remove(message);
em.remove(message);
message=null;
}
@Remove
public void destroy() {}
}]]></programlisting>
<calloutlist>
<callout arearefs="messages-datamodel">
<para> The <literal>@DataModel</literal> annotation exposes an attribute of type
<literal>java.util.List</literal> to the JSF page as an instance of
<literal>javax.faces.model.DataModel</literal>. This allows us to use the list
in a JSF <literal><h:dataTable></literal> with clickable links for
each row. In this case, the <literal>DataModel</literal> is made available in a
session context variable named <literal>messageList</literal>. </para>
</callout>
<callout arearefs="messages-datamodelselection">
<para> The <literal>@DataModelSelection</literal> annotation tells Seam to inject the
<literal>List</literal> element that corresponded to the clicked link. </para>
</callout>
<callout arearefs="messages-out">
<para> The <literal>@Out</literal> annotation then exposes the selected value directly
to the page. So every time a row of the clickable list is selected, the
<literal>Message</literal> is injected to the attribute of the stateful bean,
and the subsequently <emphasis>outjected</emphasis> to the event context variable
named <literal>message</literal>. </para>
</callout>
<callout arearefs="messages-persistencecontext">
<para> This stateful bean has an JPA <emphasis>extended persistence context</emphasis>.
The messages retrieved in the query remain in the managed state as long as the bean
exists, so any subsequent method calls to the stateful bean can update them without
needing to make any explicit call to the <literal>EntityManager</literal>. </para>
</callout>
<callout arearefs="messages-factory">
<para> The first time we navigate to the JSF page, there will be no value in the
<literal>messageList</literal> context variable. The <literal>@Factory</literal>
annotation tells Seam to create an instance of <literal>MessageManagerBean</literal>
and invoke the <literal>findMessages()</literal> method to initialize the value. We
call <literal>findMessages()</literal> a <emphasis>factory method</emphasis> for
<literal>messages</literal>. </para>
</callout>
<callout arearefs="messages-select">
<para> The <literal>select()</literal> action listener method marks the selected
<literal>Message</literal> as read, and updates it in the database. </para>
</callout>
<callout arearefs="messages-delete">
<para> The <literal>delete()</literal> action listener method removes the selected
<literal>Message</literal> from the database. </para>
</callout>
<callout arearefs="messages-remove">
<para> All stateful session bean Seam components <emphasis>must</emphasis> have a method
with no parameters marked <literal>@Remove</literal> that Seam uses to remove
the stateful bean when the Seam context ends, and clean up any server-side state.
</para>
</callout>
</calloutlist>
</programlistingco>
</example>
<para> Note that this is a session-scoped Seam component. It is associated with the user login session,
and all requests from a login session share the same instance of the component. (In Seam
applications, we usually use session-scoped components sparingly.) </para>
</section>
<section>
<title>The session bean local interface: <literal>MessageManager.java</literal></title>
<para> All session beans have a business interface, of course. </para>
<example>
<title>MessageManager.java</title>
<programlisting role="JAVA"><![CDATA[@Local
public interface MessageManager
{
public void findMessages();
public void select();
public void delete();
public void destroy();
}]]></programlisting></example>
<para> From now on, we won't show local interfaces in our code examples. </para>
<para> Let's skip over <literal>components.xml</literal>, <literal>persistence.xml</literal>,