This repository has been archived by the owner on Nov 10, 2017. It is now read-only.
forked from VaclavDedik/jboss-seam
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Events.xml
executable file
·1223 lines (1002 loc) · 53.4 KB
/
Events.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="events">
<title>Events, interceptors and exception handling</title>
<para>
Complementing the contextual component model, there are two further basic concepts
that facilitate the extreme loose-coupling that is the distinctive feature of Seam
applications. The first is a strong event model where events may be mapped to event
listeners via JSF-like method binding expressions. The second is the pervasive use
of annotations and interceptors to apply cross-cutting concerns to components which
implement business logic.
</para>
<section>
<title>Seam events</title>
<para>
The Seam component model was developed for use with <emphasis>event-driven
applications</emphasis>, specifically to enable the development of fine-grained,
loosely-coupled components in a fine-grained eventing model. Events in Seam come
in several types, most of which we have already seen:
</para>
<itemizedlist>
<listitem>
<para>JSF events</para>
</listitem>
<listitem>
<para>jBPM transition events</para>
</listitem>
<listitem>
<para>Seam page actions</para>
</listitem>
<listitem>
<para>Seam component-driven events</para>
</listitem>
<listitem>
<para>Seam contextual events</para>
</listitem>
</itemizedlist>
<para>
All of these various kinds of events are mapped to Seam components via JSF EL
method binding expressions. For a JSF event, this is defined in the JSF template:
</para>
<programlisting role="XHTML"><![CDATA[<h:commandButton value="Click me!" action="#{helloWorld.sayHello}"/>]]></programlisting>
<para>
For a jBPM transition event, it is specified in the jBPM process definition or
pageflow definition:
</para>
<programlisting role="XML"><![CDATA[<start-page name="hello" view-id="/hello.xhtml">
<transition to="hello">
<action expression="#{helloWorld.sayHello}"/>
</transition>
</start-page>]]></programlisting>
<para>
You can find out more information about JSF events and jBPM events elsewhere.
Let's concentrate for now upon the two additional kinds of events defined by Seam.
</para>
</section>
<section>
<title>Page actions</title>
<para>
A Seam page action is an event that occurs just before we render a page.
We declare page actions in <literal>WEB-INF/pages.xml</literal>. We
can define a page action for either a particular JSF view id:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/hello.xhtml" action="#{helloWorld.sayHello}"/>
</pages>]]></programlisting>
<para>
Or we can use a <literal>*</literal> wildcard as a suffix to the
<literal>view-id</literal> to specify an action that applies to all
view ids that match the pattern:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/hello/*" action="#{helloWorld.sayHello}"/>
</pages>]]></programlisting>
<para>
Keep in mind that if the <literal><page></literal> element is defined in
a fine-grained page descriptor, the <literal>view-id</literal> attribute
can be left off since it is implied.
</para>
<para>
If multiple wildcarded page actions match the current view-id, Seam
will call all the actions, in order of least-specific to most-specific.
</para>
<para>
The page action method can return a JSF outcome. If the outcome is
non-null, Seam will use the defined navigation rules to navigate to a view.
</para>
<para>
Furthermore, the view id mentioned in the <literal><page></literal>
element need not correspond to a real JSP or Facelets page! So, we can
reproduce the functionality of a traditional action-oriented framework
like Struts or WebWork using page actions. This is quite useful if you want
to do complex things in response to non-faces requests (for example, HTTP GET
requests).
</para>
<para>
Multiple or conditional page actions my be specified using the <literal><action></literal>
tag:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/hello.xhtml">
<action execute="#{helloWorld.sayHello}" if="#{not validation.failed}"/>
<action execute="#{hitCount.increment}"/>
</page>
</pages>]]></programlisting>
<para>
Page actions are executed on both an initial (non-faces) request and a postback (faces) request.
If you are using the page action to load data, this operation may conflict with the standard JSF
action(s) being executed on a postback. One way to disable the page action is to setup a condition
that resolves to true only on an initial request.
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/dashboard.xhtml">
<action execute="#{dashboard.loadData}"
if="#{not facesContext.renderKit.responseStateManager.isPostback(facesContext)}"/>
</page>
</pages>]]></programlisting>
<para>
This condition consults the <literal>ResponseStateManager#isPostback(FacesContext)</literal> to
determine if the request is a postback. The ResponseStateManager is accessed using
<literal>FacesContext.getCurrentInstance().getRenderKit().getResponseStateManager()</literal>.
</para>
<para>
To save you from the verbosity of JSF's API, Seam offers a built-in condition that allows you to
accomplish the same result with a heck of a lot less typing. You can disable a page action on postback
by simply setting the <literal>on-postback</literal> to <literal>false</literal>:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/dashboard.xhtml">
<action execute="#{dashboard.loadData}" on-postback="false"/>
</page>
</pages>]]></programlisting>
<para>
For backwards compatibility reasons, the default value of the <literal>on-postback</literal> attribute
is true, though likely you will end up using the opposite setting more often.
</para>
</section>
<section>
<title>Page parameters</title>
<para>
A JSF faces request (a form submission) encapsulates both an "action"
(a method binding) and "parameters" (input value bindings). A page
action might also needs parameters!
</para>
<para>
Since GET requests are bookmarkable, page parameters are passed as
human-readable request parameters. (Unlike JSF form inputs, which are
anything but!)
</para>
<para>
You can use page parameters with or without an action method.
</para>
<section>
<title>Mapping request parameters to the model</title>
<para>
Seam lets us provide a value binding that maps a named request parameter
to an attribute of a model object.
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/hello.xhtml" action="#{helloWorld.sayHello}">
<param name="firstName" value="#{person.firstName}"/>
<param name="lastName" value="#{person.lastName}"/>
</page>
</pages>]]></programlisting>
<para>
The <literal><param></literal> declaration is bidirectional, just
like a value binding for a JSF input:
</para>
<itemizedlist>
<listitem>
<para>
When a non-faces (GET) request for the view id occurs, Seam sets
the value of the named request parameter onto the model object,
after performing appropriate type conversions.
</para>
</listitem>
<listitem>
<para>
Any <literal><s:link></literal> or <literal><s:button></literal>
transparently includes the request parameter. The value of the parameter is
determined by evaluating the value binding during the render phase (when the
<literal><s:link></literal> is rendered).
</para>
</listitem>
<listitem>
<para>
Any navigation rule with a <literal><redirect/></literal> to
the view id transparently includes the request parameter. The value
of the parameter is determined by evaluating the value binding at
the end of the invoke application phase.
</para>
</listitem>
<listitem>
<para>
The value is transparently propagated with any JSF form submission
for the page with the given view id. This means that view parameters
behave like <literal>PAGE</literal>-scoped context variables for
faces requests.
</para>
</listitem>
</itemizedlist>
<para>
The essential idea behind all this is that <emphasis>however</emphasis>
we get from any other page to <literal>/hello.xhtml</literal> (or from
<literal>/hello.xhtml</literal> back to <literal>/hello.xhtml</literal>),
the value of the model attribute referred to in the value binding is
"remembered", without the need for a conversation (or other server-side
state).
</para>
</section>
</section>
<section>
<title>Propagating request parameters</title>
<para>
If just the <literal>name</literal> attribute is specified then the
request parameter is propagated using the <literal>PAGE</literal> context
(it isn't mapped to model property).
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/hello.xhtml" action="#{helloWorld.sayHello}">
<param name="firstName" />
<param name="lastName" />
</page>
</pages>]]></programlisting>
<para>
Propagation of page parameters is especially useful if you want to build multi-layer
master-detail CRUD pages. You can use it to "remember" which view you were previously
on (e.g. when pressing the Save button), and which entity you were editing.
</para>
<itemizedlist>
<listitem>
<para>
Any <literal><s:link></literal> or <literal><s:button></literal>
transparently propagates the request parameter if that parameter is listed
as a page parameter for the view.
</para>
</listitem>
<listitem>
<para>
The value is transparently propagated with any JSF form submission
for the page with the given view id. (This means that view parameters
behave like <literal>PAGE</literal>-scoped context variables for
faces requests.
</para>
</listitem>
</itemizedlist>
<para>
This all sounds pretty complex, and you're probably wondering if such an
exotic construct is really worth the effort. Actually, the idea is very
natural once you "get it". It is definitely worth taking the time to
understand this stuff. Page parameters are the most elegant way to
propagate state across a non-faces request. They are especially cool for
problems like search screens with bookmarkable results pages, where we
would like to be able to write our application code to handle both POST
and GET requests with the same code. Page parameters eliminate repetitive
listing of request parameters in the view definition and make redirects
much easier to code.
</para>
</section>
<section>
<title>URL rewriting with page parameters</title>
<para>
Rewriting occurs based on rewrite patterns found for views in <literal>pages.xml</literal>.
Seam URL rewriting does both incoming and outgoing URL rewriting based on the same pattern.
Here's a simple pattern:
</para>
<programlisting role="XML"><![CDATA[
<page view-id="/home.xhtml">
<rewrite pattern="/home" />
</page>
]]></programlisting>
<para>
In this case, any incoming request for <literal>/home</literal> will be sent to
<literal>/home.xhtml</literal>. More interestingly,
any link generated that would normally point to <literal>/home.seam</literal> will
instead be rewritten as <literal>/home</literal>. Rewrite patterns only match the portion of the URL
before the query parameters. So, <literal>/home.seam?conversationId=13</literal> and
<literal>/home.seam?color=red</literal>
will both be matched by this rewrite rule.
</para>
<para>
Rewrite rules can take these query paramters into consideration, as shown with the following rules.
</para>
<programlisting role="XML"><![CDATA[
<page view-id="/home.xhtml">
<rewrite pattern="/home/{color}" />
<rewrite pattern="/home" />
</page>
]]></programlisting>
<para>
In this case, an incoming request for <literal>/home/red</literal> will be served as
if it were a request
for <literal>/home.seam?color=red</literal>. Similarly, if color is a page parameter an outgoing
URL that would normally show as <literal>/home.seam?color=blue</literal> would instead
be output as
<literal>/home/blue</literal>. Rules are processed in order, so it is important to list
more specific rules before more general rules.
</para>
<para>Default Seam query parameters can also be mapped using URL rewriting, allowing for another
option for hiding Seam's fingerprints.
In the following example, <literal>/search.seam?conversationId=13</literal> would
be written as <literal>/search-13</literal>.
</para>
<programlisting role="XML"><![CDATA[
<page view-id="/search.xhtml">
<rewrite pattern="/search-{conversationId}" />
<rewrite pattern="/search" />
</page>
]]></programlisting>
<para>
Seam URL rewriting provides simple, bidirectional rewriting on a per-view basis. For more
complex rewriting rules that cover non-seam components, Seam applications can continue to
use the <literal>org.tuckey URLRewriteFilter </literal>or apply rewriting rules at the web server.
</para>
<para>
URL rewriting requires the Seam rewrite filter to be enable. Rewrite filter
configuration is discussed in <xref linkend="configuration.filters.rewrite"/>.
</para>
</section>
<section>
<title>Conversion and Validation</title>
<para>
You can specify a JSF converter for complex model properties:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/calculator.xhtml" action="#{calculator.calculate}">
<param name="x" value="#{calculator.lhs}"/>
<param name="y" value="#{calculator.rhs}"/>
<param name="op" converterId="com.my.calculator.OperatorConverter" value="#{calculator.op}"/>
</page>
</pages>]]></programlisting>
<para>
Alternatively:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/calculator.xhtml" action="#{calculator.calculate}">
<param name="x" value="#{calculator.lhs}"/>
<param name="y" value="#{calculator.rhs}"/>
<param name="op" converter="#{operatorConverter}" value="#{calculator.op}"/>
</page>
</pages>]]></programlisting>
<para>
JSF validators, and <literal>required="true"</literal> may
also be used:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/blog.xhtml">
<param name="date"
value="#{blog.date}"
validatorId="com.my.blog.PastDate"
required="true"/>
</page>
</pages>]]></programlisting>
<para>
Alternatively:
</para>
<programlisting role="XML"><![CDATA[<pages>
<page view-id="/blog.xhtml">
<param name="date"
value="#{blog.date}"
validator="#{pastDateValidator}"
required="true"/>
</page>
</pages>]]></programlisting>
<para>
Even better, model-based Hibernate validator annotations are automatically
recognized and validated. Seam also provides a default date converter to
convert a string parameter value to a date and back.
</para>
<para>
When type conversion or validation fails, a global <literal>FacesMessage</literal>
is added to the <literal>FacesContext</literal>.
</para>
</section>
<section id="events.pageaction.navigation">
<title>Navigation</title>
<para>
You can use standard JSF navigation rules defined in <literal>faces-config.xml</literal>
in a Seam application. However, JSF navigation rules have a number of annoying
limitations:
</para>
<itemizedlist>
<listitem>
<para>
It is not possible to specify request parameters to be used when redirecting.
</para>
</listitem>
<listitem>
<para>
It is not possible to begin or end conversations from a rule.
</para>
</listitem>
<listitem>
<para>
Rules work by evaluating the return value of the action method; it is not
possible to evaluate an arbitrary EL expression.
</para>
</listitem>
</itemizedlist>
<para>
A further problem is that "orchestration" logic gets scattered between <literal>pages.xml</literal>
and <literal>faces-config.xml</literal>. It's better to unify this logic into <literal>pages.xml</literal>.
</para>
<para>
This JSF navigation rule:
</para>
<programlisting role="XML"><![CDATA[<navigation-rule>
<from-view-id>/editDocument.xhtml</from-view-id>
<navigation-case>
<from-action>#{documentEditor.update}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/viewDocument.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>]]></programlisting>
<para>
Can be rewritten as follows:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<rule if-outcome="success">
<redirect view-id="/viewDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
<para>
But it would be even nicer if we didn't have to pollute our <literal>DocumentEditor</literal>
component with string-valued return values (the JSF outcomes). So Seam lets us write:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}"
evaluate="#{documentEditor.errors.size}">
<rule if-outcome="0">
<redirect view-id="/viewDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
<para>
Or even:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<rule if="#{documentEditor.errors.empty}">
<redirect view-id="/viewDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
<para>
The first form evaluates a value binding to determine the outcome value
to be used by the subsequent rules.
The second approach ignores the outcome and evaluates a value binding
for each possible rule.
</para>
<para>
Of course, when an update succeeds, we probably want to end the current
conversation. We can do that like this:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<rule if="#{documentEditor.errors.empty}">
<end-conversation/>
<redirect view-id="/viewDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
<para>
As we've ended conversation any subsequent requests won't know
which document we are interested in. We can pass the document
id as a request parameter which also makes the view bookmarkable:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<rule if="#{documentEditor.errors.empty}">
<end-conversation/>
<redirect view-id="/viewDocument.xhtml">
<param name="documentId" value="#{documentEditor.documentId}"/>
</redirect>
</rule>
</navigation>
</page>]]></programlisting>
<para>
Null outcomes are a special case in JSF. The null outcome is interpreted to
mean "redisplay the page". The following navigation rule matches any non-null
outcome, but <emphasis>not</emphasis> the null outcome:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<rule>
<render view-id="/viewDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
<para>
If you want to perform navigation when a null outcome occurs, use the
following form instead:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation from-action="#{documentEditor.update}">
<render view-id="/viewDocument.xhtml"/>
</navigation>
</page>]]></programlisting>
<para>
The view-id may be given as a JSF EL expression:
</para>
<programlisting role="XML"><![CDATA[<page view-id="/editDocument.xhtml">
<navigation>
<rule if-outcome="success">
<redirect view-id="/#{userAgent}/displayDocument.xhtml"/>
</rule>
</navigation>
</page>]]></programlisting>
</section>
<section>
<title>Fine-grained files for definition of navigation, page actions and parameters</title>
<para>
If you have a lot of different page actions and page parameters,
or even just a lot of navigation rules,
you will almost certainly want to split the declarations up over
multiple files. You can define actions and parameters for a page
with the view id <literal>/calc/calculator.xhtml</literal> in a
resource named <literal>calc/calculator.page.xml</literal>. The
root element in this case is the <literal><page></literal>
element, and the view id is implied:
</para>
<programlisting role="XML"><![CDATA[<page action="#{calculator.calculate}">
<param name="x" value="#{calculator.lhs}"/>
<param name="y" value="#{calculator.rhs}"/>
<param name="op" converter="#{operatorConverter}" value="#{calculator.op}"/>
</page>]]></programlisting>
</section>
<section>
<title>Component-driven events</title>
<para>
Seam components can interact by simply calling each others methods.
Stateful components may even implement the observer/observable pattern.
But to enable components to interact in a more loosely-coupled fashion
than is possible when the components call each others methods directly,
Seam provides <emphasis>component-driven events</emphasis>.
</para>
<para>
We specify event listeners (observers) in <literal>components.xml</literal>.
</para>
<programlisting role="XML"><![CDATA[<components>
<event type="hello">
<action execute="#{helloListener.sayHelloBack}"/>
<action execute="#{logger.logHello}"/>
</event>
</components>]]></programlisting>
<para>
Where the <emphasis>event type</emphasis> is just an arbitrary string.
</para>
<para>
When an event occurs, the actions registered for that event will be called
in the order they appear in <literal>components.xml</literal>. How does a
component raise an event? Seam provides a built-in component for this.
</para>
<programlisting role="JAVA"><![CDATA[@Name("helloWorld")
public class HelloWorld {
public void sayHello() {
FacesMessages.instance().add("Hello World!");
Events.instance().raiseEvent("hello");
}
}]]></programlisting>
<para>
Or you can use an annotation.
</para>
<programlisting role="JAVA"><![CDATA[@Name("helloWorld")
public class HelloWorld {
@RaiseEvent("hello")
public void sayHello() {
FacesMessages.instance().add("Hello World!");
}
}]]></programlisting>
<para>
Notice that this event producer has no dependency upon event consumers.
The event listener may now be implemented with absolutely no dependency
upon the producer:
</para>
<programlisting role="JAVA"><![CDATA[@Name("helloListener")
public class HelloListener {
public void sayHelloBack() {
FacesMessages.instance().add("Hello to you too!");
}
}]]></programlisting>
<para>
The method binding defined in <literal>components.xml</literal> above
takes care of mapping the event to the consumer.
If you don't like futzing about in the <literal>components.xml</literal>
file, you can use an annotation instead:
</para>
<programlisting role="JAVA"><![CDATA[@Name("helloListener")
public class HelloListener {
@Observer("hello")
public void sayHelloBack() {
FacesMessages.instance().add("Hello to you too!");
}
}]]></programlisting>
<para>
You might wonder why I've not mentioned anything about event objects in
this discussion. In Seam, there is no need for an event object to propagate
state between event producer and listener. State is held in the Seam
contexts, and is shared between components. However, if you really want
to pass an event object, you can:
</para>
<programlisting role="JAVA"><![CDATA[@Name("helloWorld")
public class HelloWorld {
private String name;
public void sayHello() {
FacesMessages.instance().add("Hello World, my name is #0.", name);
Events.instance().raiseEvent("hello", name);
}
}]]></programlisting>
<programlisting role="JAVA"><![CDATA[@Name("helloListener")
public class HelloListener {
@Observer("hello")
public void sayHelloBack(String name) {
FacesMessages.instance().add("Hello #0!", name);
}
}]]></programlisting>
</section>
<section>
<title>Contextual events</title>
<para>
Seam defines a number of built-in events that the application can use to
perform special kinds of framework integration. The events are:
</para>
<itemizedlist>
<listitem><para><literal>org.jboss.seam.validationFailed</literal> — called when JSF validation fails</para></listitem>
<listitem><para><literal>org.jboss.seam.noConversation</literal> — called when there is no long running conversation and a long running conversation is required</para></listitem>
<listitem><para><literal>org.jboss.seam.preSetVariable.<name></literal> — called when the context variable <name> is set</para></listitem>
<listitem><para><literal>org.jboss.seam.postSetVariable.<name></literal> — called when the context variable <name> is set</para></listitem>
<listitem><para><literal>org.jboss.seam.preRemoveVariable.<name></literal> — called when the context variable <name> is unset</para></listitem>
<listitem><para><literal>org.jboss.seam.postRemoveVariable.<name></literal> — called when the context variable <name> is unset</para></listitem>
<listitem><para><literal>org.jboss.seam.preDestroyContext.<SCOPE></literal> — called before the <SCOPE> context is destroyed</para></listitem>
<listitem><para><literal>org.jboss.seam.postDestroyContext.<SCOPE></literal> — called after the <SCOPE> context is destroyed</para></listitem>
<listitem><para><literal>org.jboss.seam.beginConversation </literal> — called whenever a long-running conversation begins</para></listitem>
<listitem><para><literal>org.jboss.seam.endConversation </literal> — called whenever a long-running conversation ends</para></listitem>
<listitem><para><literal>org.jboss.seam.conversationTimeout</literal> — called when a conversation timeout occurs. The conversation id is passed as a parameter.</para></listitem>
<listitem><para><literal>org.jboss.seam.beginPageflow </literal> — called when a pageflow begins</para></listitem>
<listitem><para><literal>org.jboss.seam.beginPageflow.<name> </literal> — called when the pageflow <name> begins</para></listitem>
<listitem><para><literal>org.jboss.seam.endPageflow </literal> — called when a pageflow ends</para></listitem>
<listitem><para><literal>org.jboss.seam.endPageflow.<name> </literal> — called when the pageflow <name> ends</para></listitem>
<listitem><para><literal>org.jboss.seam.createProcess.<name> </literal> — called when the process <name> is created</para></listitem>
<listitem><para><literal>org.jboss.seam.endProcess.<name> </literal> — called when the process <name> ends</para></listitem>
<listitem><para><literal>org.jboss.seam.initProcess.<name> </literal> — called when the process <name> is associated with the conversation</para></listitem>
<listitem><para><literal>org.jboss.seam.initTask.<name> </literal> — called when the task <name> is associated with the conversation</para></listitem>
<listitem><para><literal>org.jboss.seam.startTask.<name> </literal> — called when the task <name> is started</para></listitem>
<listitem><para><literal>org.jboss.seam.endTask.<name> </literal> — called when the task <name> is ended</para></listitem>
<listitem><para><literal>org.jboss.seam.postCreate.<name> </literal> — called when the component <name> is created</para></listitem>
<listitem><para><literal>org.jboss.seam.preDestroy.<name> </literal> — called when the component <name> is destroyed</para></listitem>
<listitem><para><literal>org.jboss.seam.beforePhase </literal> — called before the start of a JSF phase</para></listitem>
<listitem><para><literal>org.jboss.seam.afterPhase </literal> — called after the end of a JSF phase</para></listitem>
<listitem><para><literal>org.jboss.seam.postInitialization </literal> — called when Seam has initialized and started up all components</para></listitem>
<listitem><para><literal>org.jboss.seam.postReInitialization </literal> — called when Seam has re-initialized and started up all components after a redeploy</para></listitem>
<listitem><para><literal>org.jboss.seam.exceptionHandled.<type></literal> — called when an uncaught exception is handled by Seam</para></listitem>
<listitem><para><literal>org.jboss.seam.exceptionHandled</literal> — called when an uncaught exception is handled by Seam</para></listitem>
<listitem><para><literal>org.jboss.seam.exceptionNotHandled</literal> — called when there was no handler for an uncaught exception</para></listitem>
<listitem><para><literal>org.jboss.seam.afterTransactionSuccess</literal> — called when a transaction succeeds in the Seam Application Framework</para></listitem>
<listitem><para><literal>org.jboss.seam.afterTransactionSuccess.<name></literal> — called when a transaction succeeds in the Seam Application Framework which manages an entity called <literal><name></literal></para></listitem>
<listitem><para><literal>org.jboss.seam.security.loggedOut</literal> — called when a user logs out</para></listitem>
<listitem><para><literal>org.jboss.seam.security.loginFailed</literal> — called when a user authentication attempt fails</para></listitem>
<listitem><para><literal>org.jboss.seam.security.loginSuccessful</literal> — called when a user is successfully authenticated</para></listitem>
<listitem><para><literal>org.jboss.seam.security.notAuthorized</literal> — called when an authorization check fails</para></listitem>
<listitem><para><literal>org.jboss.seam.security.notLoggedIn</literal> — called there is no authenticated user and authentication is required</para></listitem>
<listitem><para><literal>org.jboss.seam.security.postAuthenticate.</literal> — called after a user is authenticated</para></listitem>
<listitem><para><literal>org.jboss.seam.security.preAuthenticate</literal> — called before attempting to authenticate a user</para></listitem>
</itemizedlist>
<para>
Seam components may observe any of these events in just the same way they
observe any other component-driven events.
</para>
</section>
<section>
<title>Seam interceptors</title>
<para>
EJB 3.0 introduced a standard interceptor model for session bean components. To add an
interceptor to a bean, you need to write a class with a method annotated
<literal>@AroundInvoke</literal> and annotate the bean with an
<literal>@Interceptors</literal> annotation that specifies the name of the interceptor
class. For example, the following interceptor checks that the user is logged in before
allowing invoking an action listener method:
</para>
<programlisting role="JAVA"><![CDATA[public class LoggedInInterceptor {
@AroundInvoke
public Object checkLoggedIn(InvocationContext invocation) throws Exception {
boolean isLoggedIn = Contexts.getSessionContext().get("loggedIn")!=null;
if (isLoggedIn) {
//the user is already logged in
return invocation.proceed();
}
else {
//the user is not logged in, fwd to login page
return "login";
}
}
}]]></programlisting>
<para>
To apply this interceptor to a session bean which acts as an action listener, we must
annotate the session bean <literal>@Interceptors(LoggedInInterceptor.class)</literal>.
This is a somewhat ugly annotation. Seam builds upon the interceptor framework in
EJB3 by allowing you to use <literal>@Interceptors</literal> as a meta-annotation for class
level interceptors (those annotated <literal>@Target(TYPE)</literal>). In
our example, we would create an <literal>@LoggedIn</literal> annotation, as follows:
</para>
<programlisting role="JAVA"><![CDATA[@Target(TYPE)
@Retention(RUNTIME)
@Interceptors(LoggedInInterceptor.class)
public @interface LoggedIn {}]]></programlisting>
<para>
We can now simply annotate our action listener bean with <literal>@LoggedIn</literal>
to apply the interceptor.
</para>
<programlisting role="JAVA"><![CDATA[@Stateless
@Name("changePasswordAction")
@LoggedIn
@Interceptors(SeamInterceptor.class)
public class ChangePasswordAction implements ChangePassword {
...
public String changePassword() { ... }
}]]></programlisting>
<para>
If interceptor ordering is important (it usually is), you can add
<literal>@Interceptor</literal> annotations to your interceptor
classes to specify a partial order of interceptors.
</para>
<programlisting role="JAVA"><![CDATA[@Interceptor(around={BijectionInterceptor.class,
ValidationInterceptor.class,
ConversationInterceptor.class},
within=RemoveInterceptor.class)
public class LoggedInInterceptor
{
...
}]]></programlisting>
<para>
You can even have a "client-side" interceptor, that runs around any of the built-in
functionality of EJB3:
</para>
<programlisting role="JAVA"><![CDATA[@Interceptor(type=CLIENT)
public class LoggedInInterceptor
{
...
}]]></programlisting>
<para>
EJB interceptors are stateful, with a lifecycle that is the same as the component
they intercept. For interceptors which do not need to maintain state, Seam lets
you get a performance optimization by specifying
<literal>@Interceptor(stateless=true)</literal>.
</para>
<para>
Much of the functionality of Seam is implemented as a set of built-in Seam interceptors,
including the interceptors named in the previous example. You don't have to explicitly
specify these interceptors by annotating your components; they exist for all interceptable
Seam components.
</para>
<para>
You can even use Seam interceptors with JavaBean components, not just EJB3 beans!
</para>
<para>
EJB defines interception not only for business methods (using <literal>@AroundInvoke</literal>),
but also for the lifecycle methods <literal>@PostConstruct</literal>, <literal>@PreDestroy</literal>,
<literal>@PrePassivate</literal> and <literal>@PostActive</literal>. Seam supports all these
lifecycle methods on both component and interceptor not only for EJB3 beans, but also for
JavaBean components (except <literal>@PreDestroy</literal> which is not meaningful for JavaBean
components).
</para>
</section>
<section>
<title>Managing exceptions</title>
<para>
JSF is surprisingly limited when it comes to exception handling. As a partial
workaround for this problem, Seam lets you define how a particular class of
exception is to be treated by annotating the exception class, or declaring
the exception class in an XML file. This facility is meant to be combined with
the EJB 3.0-standard <literal>@ApplicationException</literal> annotation which
specifies whether the exception should cause a transaction rollback.
</para>
<section>
<title>Exceptions and transactions</title>
<para>
EJB specifies well-defined rules that let us control whether an exception
immediately marks the current transaction for rollback when it is thrown by
a business method of the bean: <emphasis>system exceptions</emphasis> always
cause a transaction rollback, <emphasis>application exceptions</emphasis> do
not cause a rollback by default, but they do if
<literal>@ApplicationException(rollback=true)</literal>
is specified. (An application exception is any checked exception, or any
unchecked exception annotated <literal>@ApplicationException</literal>.
A system exception is any unchecked exception without an
<literal>@ApplicationException</literal> annotation.)
</para>
<para>
Note that there is a difference between marking a transaction for rollback,
and actually rolling it back. The exception rules say that the transaction
should be marked rollback only, but it may still be active after the
exception is thrown.
</para>
<para>
Seam applies the EJB 3.0 exception rollback rules also to Seam JavaBean
components.
</para>
<para>
But these rules only apply in the Seam component layer. What about an exception
that is uncaught and propagates out of the Seam component layer, and out of the JSF
layer? Well, it is always wrong to leave a dangling transaction open, so Seam
rolls back any active transaction when an exception occurs and is uncaught
in the Seam component layer.
</para>
</section>
<section>
<title>Enabling Seam exception handling</title>
<para>
To enable Seam's exception handling, we need to make sure we have the master servlet
filter declared in <literal>web.xml</literal>:
</para>
<programlisting role="XML"><![CDATA[<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>*.seam</url-pattern>
</filter-mapping>]]></programlisting>
<para>
As the second requirement is to add <literal>web:exception-filter</literal> configuration component
into <filename>WEB-INF/components.xml</filename>. More details are in <xref linkend="exception_handling"/>
</para>