初次使用Struts2,老老實(shí)實(shí)為每個(gè)action method配置url mapping文件。
時(shí)間長(zhǎng)了,難為覺(jué)得繁瑣,為何不使用COC的方式呢?終于,想到了使用通配符。
查看Struts2 Docs,找到相關(guān)配置方法:
<package name="alliance" namespace="/alliance" extends="struts-default">
<action name="*/*" class="cn.zeroall.cow.web.alliance.action.{1}Action" method="{2}">
<result name="target" type="velocity">/templates/alliance/{1}/${target}.vm</result>
<result name="success" type="velocity">/templates/alliance/{1}/{2}.vm</result>
<result name="input" type="velocity">/templates/alliance/{1}/{2}.vm</result>
<result name="fail" type="velocity">/templates/common/error.vm</result>
</action>
</package>
恩,非常方便,可是啟動(dòng)jetty,發(fā)現(xiàn)滿(mǎn)足正則的url,就是找不到Action。
無(wú)奈,debug代碼,找到原因,需要在struts.properties中,配置:
struts.enable.SlashesInActionNames = true
見(jiàn)注釋?zhuān)?br />
### Set this to true if you wish to allow slashes in your action names. If false,
### Actions names cannot have slashes, and will be accessible via any directory
### prefix. This is the traditional behavior expected of WebWork applications.
### Setting to true is useful when you want to use wildcards and store values
### in the URL, to be extracted by wildcard patterns, such as
### <action name="*/*" method="{2}" class="actions.{1}"> to match "/foo/edit" or
### "/foo/save".
啟動(dòng),COC終于成功。
但是(又冒出一個(gè)但是),針對(duì)*/*正則的url mapping,如何做validation呢?
按照struts2的約定,是通過(guò):
[package/]ActionName-${配置中的action name=""中的名字}-validation.xml
如何把"/"這個(gè)符號(hào)放入到${配置中的action name=""中的名字}呢?
"/"可不是一個(gè)合法的文件名。
比如,我要為AlliedMemberAction/doRegister做validation,那么約定的校驗(yàn)文件名應(yīng)該是:
cn/zeroall/cow/web/alliance/action/AlliedMemberAction-AlliedMember
/doRegister-validation.xml
這個(gè)特殊符號(hào),可難剎我也。
無(wú)奈,繼續(xù)debug,發(fā)現(xiàn)在代碼:
xwork框架中的,AnnotationActionValidatorManager:
private List<ValidatorConfig> buildAliasValidatorConfigs(Class aClass, String context, boolean checkFile) {
String fileName = aClass.getName().replace('.', '/') + "-" + context + VALIDATION_CONFIG_SUFFIX;
return loadFile(fileName, aClass, checkFile);
}
這個(gè)context就是action name=""中的url表達(dá)式。
思想斗爭(zhēng)后,由于我不喜歡使用*-*的pattern,更喜歡使用*/*pattern,只好修改了源碼:
private List<ValidatorConfig> buildAliasValidatorConfigs(Class aClass, String context, boolean checkFile) {
String fileName = aClass.getName().replace('.', '/') + "-" + context.replace("/", "-") + VALIDATION_CONFIG_SUFFIX;
return loadFile(fileName, aClass, checkFile);
}
將context中的“/”變成"-"解決這個(gè)問(wèn)題。
不清楚struts2官方怎么看待這個(gè)問(wèn)題。
大家是否有更好的方案,請(qǐng)指教