Struts2.1.6–想用通配符,不容易

初次使用Struts2,老老实实为每个action method配置url mapping文件。

时间长了,难为觉得繁琐,为何不使用COC的方式呢?终于,想到了使用通配符。

查看Struts2 Docs,找到相关配置方法:

                      /templates/alliance/{1}/ ${target}.vm             /templates/alliance/{1}/ {2}.vm             /templates/alliance/{1}/ {2}.vm             /templates/common/error.vm        

恩,非常方便,可是启动jetty,发现满足正则的url,就是找不到Action。

无奈,debug代码,找到原因,需要在struts.properties中,配置:

struts.enable.SlashesInActionNames = true

见注释:

### 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###  to match "/foo/edit"  or### "/foo/save".

启动,COC终于成功。

但是(又冒出一个但是),针对*/*正则的url mapping,如何做validation呢?

按照struts2的约定,是通过:

[package/]ActionName-${配置中的action name=””中的名字}-validation.xml

如何把”/”这个符号放入到${配置中的action name=””中的名字}呢?

“/”可不是一个合法的文件名。

比如,我要为AlliedMemberAction/doRegister做validation,那么约定的校验文件名应该是:

cn/zeroall/cow/web/alliance/action/AlliedMemberAction-AlliedMember/doRegister- validation.xml

这个特殊符号,可难刹我也。

无奈,继续debug,发现在代码:

xwork框架中的,AnnotationActionValidaTorManager:

private  List buildAliasValidaTorConfigs(Class aClass,  String context, boolean checkFile) {         String fileName = aClass.getName().replace('.', '/') + "-" +  context + VALIDATION_CONFIG_SUFFIX;         return loadFile(fileName, aClass, checkFile);}

这个context就是action name=””中的url表达式。

思想斗争后,由于我不喜欢使用*-*的pattern,更喜欢使用*/*pattern,只好修改了源码:

private  List buildAliasValidaTorConfigs(Class aClass,  String context, boolean checkFile) {         String fileName = aClass.getName().replace('.', '/') + "-" +  context.replace("/", "-") + VALIDATION_CONFIG_SUFFIX;         return loadFile(fileName, aClass, checkFile);}

将context中的“/”变成”-“解决这个问题。

不清楚struts2官方怎么看待这个问题。

放下一处烦恼,收获一个惊喜;放下一种偏见,收获一种幸福;

Struts2.1.6–想用通配符,不容易

相关文章:

你感兴趣的文章:

标签云: