Professional Documents
Culture Documents
Struts 2 Basics
Struts 2 Basics
Topics
Key core features Request processing life-cycle Improvements made in Struts 2 (over Struts 1) Action Result & Result type Interceptor alidation !onfiguration files "ac#ages
source: Apache Struts 2 documentation
"lugga$le frame%or# arc&itecture t&at allo%s request lifecycles to $e customi'ed for eac& action( )le*i$le validation frame%or# t&at allo%s validation rules to $e decoupled from action code( +ierarc&ical approac& to internationali'ation t&at simplifies locali'ing applications(
4
Integrated dependency in,ection engine t&at manages component lifecycle and dependencies( (-y default. t&e frame%or# utili'es Spring for dependency in,ection() /odular configuration files t&at use pac#ages and namespaces to simplify managing large pro,ects %it& &undreds of actions( 0ava 1 annotations t&at reduce configuration over&ead( (0ava 1(2 is t&e minimum platform()
source: Apache Struts 2 documentation
Struts 2 Architecture
Si plifie" #esign
"rogramming t&e a$stract classes instead of interfaces is one of design pro$lem of struts1 frame%or# t&at &as $een resolved in t&e struts 2 frame%or#( /ost of t&e Struts 2 classes are $ased on interfaces and most of its core interfaces are +33" independent(
10
Intelligent #efaults
/ost configuration elements &ave a default value %&ic& can $e set according to t&e need( 3&ere are *ml-$ased default configuration files t&at can $e e*tended according to t&e need(
11
I pro!e" Results
8nli#e ActionForwards. Struts 2 Results provide fle*i$ility to create multiple type of outputs
12
P$%$ Action&s
Struts 1
Actions in Struts1 &ave dependencies on t&e servlet A"I since t&e HttpServletRequest and HttpServletResponse o$,ects are passed to t&e execute() met&od Any ,ava class %it& execute() met&od can $e used as an Action class( Actions to $e neutral to t&e underlying frame%or#
source: Apache Struts 2 documentation
Struts 2
13
ActionForms feature is no more #no%n to t&e Struts 2 frame%or#( Simple 0ava-ean flavored actions are used to put properties directly
14
)nhance" Testa*ility
3&is ena$les to test struts applications very easily %it&out resorting to moc# o$,ects(
15
9ou can create consistent pages %it& less code Struts 2 tag mar#up can $e altered $y c&anging an underlying styles&eet(
Struts 2 tags are more capa$le and result oriented( -ot& 0S" and )ree/ar#er tags are fully supported(
source: Apache Struts 2 documentation
16
Annotation Support
0ava 1 annotations can $e used as an alternative to :/7 and 0ava properties configuration
17
Stateful Chec+*o,es
18
-uic+ Start
/any c&anges can $e made on t&e fly %it&out restarting a %e$ container(
19
20
21
)asy Plug-in&s
<o additional :/7 or properties files( /etadata is e*pressed t&roug& convention and annotation
22
A/a, Support
A0A: client side validation Remote form su$mission support (%or#s %it& t&e su$mit tag as %ell) An advanced div template t&at provides dynamic reloading of partial +3/7 An advanced template t&at provides t&e a$ility to load and evaluate 0avaScript remotely An A0A:-only ta$$ed "anel implementation A ric& pu$-su$ event model Interactive auto complete tag
source: Apache Struts 2 documentation
23
Struts 0
!s1 Struts 2
Action
25
Action
26
/aps an identifier to a Action class( ?&en a request matc&es t&e action@s name. t&e frame%or# uses t&e mapping to determine &o% to process t&e request( Also specifies
28
3&e name attri$ute is matc&ed a part of t&e location requested $y a $ro%ser (or ot&er +33" client)( 3&e frame%or# %ill drop t&e &ost and application name and t&e e*tension. and matc& %&at@s in t&e middle( D*ampleE
29
Action 'a es
?it&in an application. t&e lin# to an action is usually generated $y a Struts 3ag( 3&e tag can specify t&e action $y name. and t&e frame%or# %ill render t&e default e*tension and anyt&ing else t&at is needed(
AsEform actionB>+ello>C AsEte*tfield la$elB>"lease enter your name> nameB>name>4C AsEsu$mit4C A4sEformC
source: Apache Struts 2 documentation
30
32
Action Interface
3&e default entry met&od to t&e &andler class is defined $y t&e Action interface(
pu#lic inter$ace Action % pu#lic String execute() throws &xception' (
If Action is not implemented. t&e frame%or# %ill use reflection to loo# for an execute met&od(
33
Action (etho"s
Sometimes. developers li#e to create more t&an one entry point to an Action(
)or e*ample. in t&e case of of a data-access Action. a developer mig&t %ant separate entry-points for create. retrieve. update. and delete( A different entry point can $e specified $y t&e met&od attri$ute( Aaction nameB>delete> classB>e*ample(!rudAction> met&odB>delete>C
If t&ere is no e*ecute met&od. and no ot&er met&od. specified in t&e configuration. t&e frame%or# %ill t&ro% an e*ception(
source: Apache Struts 2 documentation
34
6il"car" (etho"
/any times. a set of action mappings %ill s&are a common pattern Rat&er t&an code a separate mapping for eac& action class. you can %rite it once as a %ildcard mapping(
35
D*ample 1
Aaction nameB>H!rud> classB>e*ample(!rud> met&odB>I1J>C
+ere. a reference to >edit)rud> %ill call t&e edit met&od on an instance of t&e !rud Action class( 7i#e%ise. a reference to >delete)rud> %ill call t&e delete met&od instead(
D*ample 2
Aaction nameB>!rudKH> classB>e*ample(!rud> met&odB>I1J>C
source: Apache Struts 2 documentation
36
Action #efault
If you %ould prefer t&at an omni$us action &andle any unmatc&ed requests. you can specify a default action( If no ot&er action matc&es. t&e default action is used instead
Apac#age nameB>+ello> e*tendsB>action-default>C Adefault-action-ref nameB>8nder!onstruction>C Aaction nameB>8nder!onstruction>C AresultC48nder!onstruction(,spA4resultC A4actionC
source: Apache Struts 2 documentation
37
6il"car" #efault
8sing %ildcards is anot&er approac& to default actions( A %ildcard action at t&e end of t&e configuration can $e used to catc& unmatc&ed references(
Aaction nameB>H> C AresultC4I1J(,spA4resultC A4actionC
source: Apache Struts 2 documentation
38
Result
39
Result
3&e value of t&e String is used to select a result element( An action mapping %ill often &ave a set of results representing different possi$le outcomes(
3&ere are predefined result names (to#ens) Applications can define ot&er result names (to#ens) to matc& specific cases(
source: Apache Struts 2 documentation
40
String S8!!DSS B >success>L String <=<D B >none>L String DRR=R B >error>L String I<"83 B >input>L String 7=MI< B >login>L
41
An Action can pass $ac# a to#en li#e >success> or >error> %it&out #no%ing any ot&er implementation details( If t&e name attri$ute is not specified. t&e frame%or# %ill give it t&e name >success>( /ost results simply for%ard to a server page or template. $ut ot&er Result 3ypes can $e used to do more interesting t&ings( If a t*pe attri$ute is not specified. t&e frame%or# %ill use t&e dispatcher
source: Apache Struts 2 documentation
42
43
44
Result Types
45
5ispatc&er Result Redirect Action Result !&ain Result Redirect Result )ree/ar#er Result elocity Result "lain3e*t Result 3iles Result +ttp+eader Result Stream Result
source: Apache Struts 2 documentation
46
If a t*pe attri$ute is not specified. t&e frame%or# %ill use t&e dispatcher(
A default Result 3ype can $e set as part of t&e configuration for eac& pac#age(
7result-types: 7result-type na e89"ispatcher9 class89org1apache1struts21"ispatcher1Ser!let#ispatcherResult9 "efault89true9;: 7;result-types:
source: Apache Struts 2 documentation
47
=lo*al Results
/ost often. results are nested %it& t&e action element( -ut some results apply to multiple actions(
D*ampleE In a secure application. a client mig&t try to access a page %it&out $eing aut&ori'ed. and many actions may need access to a >logon> result(
If actions need to s&are results. a set of glo$al results can $e defined for eac& pac#age( 3&e frame%or# %ill first loo# for a local result nested in t&e action( If a local matc& is not found. t&en t&e glo$al results are c&ec#ed(
source: Apache Struts 2 documentation
48
49
#yna ic Results
A result may not $e #no%n until e*ecution time( Result values may $e retrieved from its corresponding Action implementation $y using D7 e*pressions t&at access t&e Action@s properties
50
51
In t&e code $elo%. if it returns success. t&en t&e $ro%ser %ill $e for%arded to
;7app-prefi,:; y'a espace;otherAction1actionBi"87!alue of i": 7action na e89 yAction9 class89co 1pro/ect1(yAction9: 7result na e89success9 type89re"irect-action9:otherActionBi"8A?i"@7;result: 7result na e89*ac+9 type89re"irect9:A?re"irect5RL@7;result: 7;action:
52
Action Chaining
3&e frame%or# provides t&e a$ility to c&ain multiple actions into a defined sequence or %or#flo%( 3&is feature %or#s $y applying a !&ain Result to a given Action
53
Chain Result
3&e !&ain Result is a result type t&at invo#es an Action %it& its o%n Interceptor Stac# and Result( 3&is Interceptor allo%s an Action to for%ard requests to a target Action. %&ile propagating t&e state of t&e source Action(
54
Apac#age nameB>pu$lic> e*tendsB>struts-default>C A;-- !&ain creatAccount to login. using t&e default parameter --C Aaction nameB>createAccount> classB>(((>C Aresult typeB>c&ain>CloginA4resultC A4actionC Aaction nameB>login> classB>(((>C A;-- !&ain to anot&er namespace --C Aresult typeB>c&ain>C Aparam nameB>action<ame>Cdas&$oardA4paramC Aparam nameB>namespace>C4secureA4paramC A4resultC A4actionC A4pac#ageC Apac#age nameB>secure> e*tendsB>struts-default> namespaceB>4secure>C Aaction nameB>das&$oard> classB>(((>C AresultCdas&$oard(,spA4resultC A4actionC A4pac#ageC 55 source: Apache Struts 2 documentation
Interceptor
56
6hy InterceptorsB
D*ampleE Some Actions need input validated( =t&er Actions may need a file upload to $e preprocessed( Anot&er Action mig&t need protection from a dou$le su$mit( /any Actions need dropdo%n lists and ot&er controls pre-populated $efore t&e page displays(
3&e frame%or# ma#es it easy to s&are solutions to t&ese concerns using an >Interceptor> strategy(
source: Apache Struts 2 documentation
57
58
Interceptors
Interceptors can e*ecute code $efore and after an Action is invo#ed( /ost of t&e frame%or#@s core functionality is implemented as Interceptors(
)eatures li#e dou$le-su$mit guards. type conversion. o$,ect population. validation. file upload. page preparation. and more. are all implemented %it& t&e &elp of Interceptors(
59
Interceptors C Actions
In some cases. an Interceptor mig&t #eep an Action from firing. $ecause of a dou$le-su$mit or $ecause validation failed( Interceptors can also c&ange t&e state of an Action $efore it e*ecutes(
60
Configuration of Interceptors
Interceptors can $e configured on a peraction $asis( 9our o%n custom Interceptors can $e mi*edand-matc&ed %it& t&e Interceptors $undled %it& t&e frame%or#( 3&e Interceptors are defined in a stac# t&at specifies t&e e*ecution order(
In some cases. t&e order of t&e Interceptors on t&e stac# can $e very important(
source: Apache Struts 2 documentation
61
Configurating Interceptors
Apac#age nameB>default> e*tendsB>struts-default>C AinterceptorsC Ainterceptor nameB>timer> classB>((>4C Ainterceptor nameB>logger> classB>((>4C A4interceptorsC Aaction nameB>login> classB>tutorial(7ogin>C Ainterceptor-ref nameB>timer>4C Ainterceptor-ref nameB>logger>4C Aresult nameB>input>Clogin(,spA4resultC Aresult nameB>success> typeB>redirect-action>C4secure4&omeA4resultC A4actionC A4pac#ageC
source: Apache Struts 2 documentation
62
Stac+ing Interceptors
?it& most %e$ applications. %e find ourselves %anting to apply t&e same set of Interceptors over and over again( Rat&er t&an reiterate t&e same list of Interceptors. %e can $undle t&ese Interceptors toget&er using an Interceptor Stac#(
63
Stac+ing Interceptors
Apac#age nameB>default> e*tendsB>struts-default>C AinterceptorsC Ainterceptor nameB>timer> classB>((>4C Ainterceptor nameB>logger> classB>((>4C Ainterceptor-stac# nameB>myStac#>C Ainterceptor-ref nameB>timer>4C Ainterceptor-ref nameB>logger>4C A4interceptor-stac#C A4interceptorsC Aaction nameB>login> classB>tutuorial(7ogin>C Ainterceptor-ref nameB>myStac#>4C Aresult nameB>input>Clogin(,spA4resultC Aresult nameB>success> typeB>redirect-action>C4secure4&omeA4resultC A4actionC A4pac#ageC source: Apache Struts 2 documentation
64
Interceptor Interface
Interceptors must implement t&e com.opens*mphon*.xwor+ .interceptor.,nterceptor interface 3&e A#stract,nterceptor class provides an empty implementation of init and destroy. and can $e used if t&ese met&ods are not going to $e implemented(
pu$lic interface Interceptor e*tends Seriali'a$le I void destroy()L void init()L String intercept(ActionInvocation invocation) t&ro%s D*ceptionL J source: Apache Struts 2 documentation
65
66
"arameter interceptorE Sets t&e request parameters onto t&e Action( Scope interceptorE Simple mec&anism for storing Action state in t&e session or application scope( alidation interceptorE "erforms validation using t&e validators defined in action-validation(*ml /any more
67
!onfigured in struts!de$ault.xml
source: Apache Struts 2 documentation
EieD Support
68
EieD
Reusa$le user interface tags t&at allo% for easy component-oriented development using t&emes and templates( -undled tags ranges from simple te*t fields to advanced tags li#e date pic#ers and tree vie%s( 0S37-compati$le e*pression language (=M<7) t&at e*poses properties on multiple o$,ects as if t&ey %ere a single 0ava-ean( "lugga$le Result 3ypes t&at support multiple vie% tec&nologies. including 0S". )ree/ar#er. elocity. "5). and 0asperReports(
source: Apache Struts 2 documentation
69
EieD
=ptional A0A: t&eme t&at simplifes creating interactive %e$ applications( =ptional Interceptor plugins t&at can e*ecute long-running queries in t&e $ac#ground. prevent multiple form su$missions. or &andle custom security sc&emes(
70
EieD Technologies
71
Eali"ation
72
Built-in Eali"ators
7!ali"ators: 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7!ali"ator na 7;!ali"ators: e89require"9 class89119;: e89require"string9 class89119;: e89int9 class89119;: e89"ou*le9 class89119;: e89"ate9 class89119;: e89e,pression9 class89119;: e89fiel"e,pression9 class89119;: e89e ail9 class89119;: e89url9 class89119;: e89!isitor9 class89119;: e89con!ersion9 class8911;: e89stringlength9 class89119;: e89rege,9 class89119;:
source: Apache Struts 2 documentation
73
Searc&es up t&e in&eritance tree of t&e action to find default validations for parent classes of t&e Action and interfaces implemented
74
75
Afield nameB>date>C Afield-validator typeB>date>C Aparam nameB>min>C1242242PP2A4paramC Aparam nameB>ma*>C1242142PP2A4paramC AmessageC3&e date must $e $et%een 12-22-2PP2 and 12-212PP2(A4messageC A4field-validatorC A4fieldC Afield nameB>foo>C Afield-validator typeB>int>C Aparam nameB>min>CPA4paramC Aparam nameB>ma*>C1PPA4paramC Amessage #eyB>foo(range>C!ould not find foo(range;A4messageC A4field-validatorC A4fieldC Avalidator typeB>e*pression>C Aparam nameB>e*pression>Cfoo lt $ar A4paramC AmessageC)oo must $e greater t&an -ar( )oo B QIfooJ. -ar B QI$arJ(A4messageC A4validatorC 76 source: Apache Struts 2 documentation
Client Eali"ation
0avaScript client validation code is generated $y t&e frame%or# !ode you %rite
AsEform actionB>7ogin> validateB>true>C AsEte*tfield #eyB>username>4C AsEpass%ord #eyB>pass%ord> 4C AsEsu$mit4C A4sEformC
77
Client Eali"ation
78
79
Configuration Files
source: Apache Struts 2 documentation
80
struts-"efault1, l
5efines all of t&e default $undled results and interceptors and many interceptor stac#s %&ic& you can use eit&er as-is or as a $asis for your o%n application-specific interceptor stac#s( Automatically included into struts.xml file Included in t&e struts2(,ar file( In order to provide your o%n version. you can c&ange t&e struts.con$iguration.$iles setting in struts.properties file(
source: Apache Struts 2 documentation
81
struts-"efault1, l
Apac#age nameB>struts-default>C Aresult-typesC Aresult-type nameB>c&ain> classB>(((>4C Aresult-type nameB>dispatc&er> classB>(((> defaultB>true>4C ((( A4result-typesC AinterceptorsC Ainterceptor nameB>alias> classB>(((>4C Ainterceptor nameB>auto%iring> classB>(((r>4C ((( A;-- -asic stac# --C Ainterceptor-stac# nameB>$asicStac#>C Ainterceptor-ref nameB>(((>4C Ainterceptor-ref nameB>servlet-config>4C Ainterceptor-ref nameB>prepare>4C Ainterceptor-ref nameB>c&ec#$o*>4C Ainterceptor-ref nameB>params>4C Ainterceptor-ref nameB>conversionDrror>4C
82
struts1, l
3&e core configuration file for t&e frame%or# S&ould reside on t&e classpat& of t&e %e$app (generally 4?D--I<)4classes)(
83
Pac+ages
84
Pac+age
"ac#ages are a %ay to group actions. results. result types. interceptors. and interceptorstac#s into a logical configuration unit( !onceptually. pac#ages are similiar to classes in t&at t&ey can $e e*tended and &ave individual parts t&at can $e overridden $y >su$> pac#ages(
85
3&e namespace attri$ute su$divides action configurations into logical modules. eac& %it& its o%n identifying prefi*(
<amespaces avoid conflicts $et%een action names( Dac& namespace can &ave it@s o%n >menu> or >&elp> action. eac& %it& its o%n implementation(
87
88
Plug-in
89
"lug-in@s are used to e*tend t&e frame%or# ,ust $y adding a 0AR to t&e application@s classpat&( Since plugins are contained in a 0AR. t&ey are easy to s&are %it& ot&ers(
90
Bun"le" Plug-in&s
0S) plug-in RDS3 plug-in Spring plug-in 3iles plug-in SiteMrap& plug-in Sitemes& plug-in 0asperReports plug-in 0)ree!&art plug-in !onfig -ro%ser plug-in Struts 1 plug-in
source: Apache Struts 2 documentation
91
Struts 2 Tags
92
Struts 2 Tags
3&e Struts 3ags &elp you create ric& %e$ applications %it& a minimum of coding(
93
94
95
96
Struts 2 Basics
97