ITEEDU

Struts Gossip: ActionMappings 通配字符

在Struts中,您所有关于请求转发等的设定都是在struts-config.xml中定义,很快的,您的 struts-config.xml就会膨涨为好几百行,甚至好几千行。

您可以使用 模块化程序 的方式,将相关的功能设定加以分类,并撰写在不同的struts-config-xxx.xml模块设定档案中。

在Struts 1.2中新增了通配字符(wildcard)设定,您可以在struts-config.xml中使用通配字符,透过事前设计好的命名规范,加上通配字符设定,您可以大量的减少struts-config.xml中的设定行数。

以一个实际的例子来看,如果您本来的struts-config.xml中的设定是这样的:
struts-config.xml
....
<action
path="/editProfile"
type="onlyfun.caterpillar.EditProfileAction"
name="profileForm"
scope="request"
validate="false">
<forward
name="failure"
path="/mainMenu.jsp"/>
<forward
name="success"
path="/profile.jsp"/>
</action>

<action
path="/editDocument"
type="onlyfun.caterpillar.EditDocumentAction"
name="documentForm"
scope="request"
validate="false">
<forward
name="failure"
path="/mainMenu.jsp"/>
<forward
name="success"
path="/document.jsp"/>
</action>
....
则在Struts 1.2中可以这么撰写就好了:
>struts-config.xml
....
<action
path="/edit*"
type="onlyfun.caterpillar.Edit{1}Action"
name="{1}Form"
scope="request"
validate="false">
<forward
name="failure"
path="/mainMenu.jsp"/>
<forward
name="success"
path="/{1}.jsp"/>
</action>
....
如上设定,如果是edit开头的请求,就会与通配字符比对,并将除去前缀部份字符串作为查找Action的依据,例如 /editProfile.do就会查找EditProfileAction的action设定,而/editDocument.do就会查找 EditDocumentAction的action设定。

通配字符*最多可以设定九个,依序对应至{1}到{9},例如/edit*Profile*.do与edit{1}Profile{2}Action的关系。

设定{0}的话,表示会包括整个请求,即包括前缀,例如/edit*.do与Admin{0}Action的关系的一个例子是,在请求为 /editProfile.do时,会呼叫AdminEditProfileAction这个action。

通配字符设定主要包括以下:
* 比对一个或多个字符,不包括斜线 ('/') 字符
** 比对一个或多个字符,包括斜线 ('/') 字符
\character 反斜线字符被用于跳脱字符,所以 \* 会用于比对星号 ('*'),而 \\ 比对反斜线 ('\').


目前Struts 1.2中 <action-mappings> 支持通配字符设定的属性有:
  • type
  • name
  • roles
  • parameter
  • attribute
  • forward
  • include
  • input