struts2的配置文件是 struts.xml,在这个配置文件里面可以使用通配符。其中的好处就是,大大减少了配置文件的内容,当然,相应付出的代价是可读性比较差。 struts2通配符的使用方法:形式一:调用相同Action中的不同方法
: C0 C4 |7 E& A+ ~2 T T0 Z- b<action name="*Action" method="{1}">; t6 s* t1 C- M
<result name="input">/login.jsp</result>
7 X' s, ] k- P" }: c' q<result name="error">/error.jsp</result>& K: p, ?6 s+ n3 x
<result name="success">/welcome.jsp</result>& w2 ~/ m# l) i! w. W' Q8 m* [
</action>
5 D3 v9 u# S" E; H+ j. n其中表达式{1}的值--->name属性值中第一个*的值。
& t% c; p( V3 O6 E a如果用户请求的URL为loginAction.action,则调用LoginRegistAction中的login方法;
j1 V. H: L6 A* n+ ?1 B4 ?* P- l" K如果用户请求的URL为registerAction.action,则调用LoginRegistAction中的register方法;
2 _/ ?* m# K& a3 r$ I; v形式二:通过匹配,调用不同的Action的execute方法
! I; i K0 G6 F# c3 u<action name="*Action">
" j/ G3 M; J. f; i: L2 C<result name="input">/login.jsp</result>
0 `( m0 V9 F0 W6 ~- G$ G3 ?! A0 `<result name="error">/error.jsp</result>& G- z: d$ ^. [, O
<result name="success">/welcome.jsp</result>: @8 z$ U3 [% V, g: [! w* G+ t- M
</action>4 @; d! H0 L7 l3 h$ ^
上面没有出现method属性,故默认调用对应的execute方法
/ ?2 x: {8 Q$ T- }& {, q6 x如果用户请求的URL为LoginAction.action,则调用LoginAction中的execute方法;
5 h) ?# e F; Y, Q& w如果用户请求的URL为RegisterAction.action,则调用RegisterAction中的execute方法;; b! r( l" o! E6 j, r# P6 `
形式三:动态结果$ K7 J8 l' Q \
<action name="crud_*" method="{1}">9 y8 z: M( ^, Y1 \
<result name="input">/input.jsp</result>
2 _4 |# s! k* v<result>/{1}.jsp</result>$ C8 q# ]9 ?% X' g
</action>
6 D0 D# V! P h9 ^当处理结果是success时,' N1 R' h) G( q4 a* C
如果crud_create.action,则会执行CrudAction中的create方法,并且跳转到/create.jsp;
8 K/ M" j; V" y" p$ z如果crud_delete.action,则会执行CrudAction中的delete方法,并且跳转到/delete.jsp; struts2通配符注意事项:最后需要注意的一点是匹配的优先权。+ V3 i. C2 \: P4 ^: R( y
(1)如果struts.xml里面有对应的action name。就算它有其他通配符匹配的,都优先对应完全相同的.
) e( i5 c; W/ A) L7 c9 z比如,有一个 action name 是 "user_add" 还有一个是 "user_*" .现在,来一个请求是 "user_add.action " .那么,它会优先匹配"user_add " 。其实,这个很好理解。
0 B4 F6 d" w9 Y8 E3 r(2)如果一个action name对应于两个带通配符的action name 那么,需要看这个配置谁在前面。它匹配写在前面的, U# }/ z; C) o* ?
比如 有一个 action name 是 "*_*" 还有一个是 "user_*" 。现在,来一个请求是 "user_add.action "。那么,它会优先匹配写在前面的。! n2 i! N3 h5 d a% ^' T
任何带"*"的action name 优先权都是一样的。不是说带一个"*"的优先权就比带两个"*" 的高。
8 m3 j- D/ t" d* ^$ v; L2 V5 J |